循环队列(Circular Queue
顺序队列
顺序队列是一种只能在表的一端进行插入运算,在表的另一端进行删除运算的线性表(头删尾插)会出现假溢出。
Rear = N - 1 时队满。
循环队列
Front == Rear 时队列为空
Front == (Rear +1 ) % queueSize 时队满
人为浪费一个空间。
代码实现
class MyCircularQueue {
private int[] queue;
private int head = 0;
private int tail = 0;
private int size;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
this.queue = new int[k + 1]; /*需要一位空出区分队满和队空*/
this.size = k + 1;/*容量为k 但大小是k+1*/
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if(isFull()){
return false;
}
queue[tail] = value;
tail = (tail + 1) % size;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if(isEmpty()) return false;
head = (head + 1) % size;
return true;
}
/** Get the front item from the queue. */
public int Front() {
return isEmpty() ? -1 : queue[head];
}
/** Get the last item from the queue. */
public int Rear() {
return isEmpty() ? -1 : queue[(tail + size - 1) % size];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return head == tail;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return (tail + 1) % size == head;
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* boolean param_1 = obj.enQueue(value);
* boolean param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* boolean param_5 = obj.isEmpty();
* boolean param_6 = obj.isFull();
*/