public class CircularQueue {
private int[] data;
private int head;
private int tail;
private int size;
public CircularQueue(int k) {
data = new int[k];
head = -1;
tail = -1;
size = k;
}
public boolean enqueue(int value) {
if (isFull()) {
return false;
}
if (isEmpty()) {
head = 0;
}
tail = (tail + 1) % size;
data[tail] = value;
return true;
}
public int dequeue() {
if (isEmpty()) {
return -1;
}
int result = data[head];
if (head == tail) {
head = -1;
tail = -1;
} else {
head = (head + 1) % size;
}
return result;
}
public boolean isEmpty() {
return head == -1;
}
public boolean isFull() {
return (tail + 1) % size == head;
}
}
这段代码实现了一个大小固定的循环队列,使用数组作为底层数据结构。它包含了入队和出队操作,并且正确处理了队列为空和为满的情况。