循环双端队列和循环队列在实现上几乎是一样的,需要注意的有以下几点:
1、定义循环变量 front 和 rear 。一直保持这个定义,到底是先赋值还是先移动指针就很容易想清楚了。
① front:指向队列头部第 1 个有效数据的位置;
② rear:指向队列尾部(即最后 1 个有效数据)的下一个位置,即下一个从队尾入队元素的位置。
2、为了避免“队列为空”和“队列为满”的判别条件冲突,我们有意浪费了一个位置。浪费一个位置是指:循环数组中任何时刻一定至少有一个位置不存放有效元素。
上图所示情况,我们就可以判定队列已经满了。
判别队列为空的条件是:front == rear;;
判别队列为满的条件:(this.rear + 1) % this.elem.length == front;
可以这样理解,当 rear 循环到数组的前面,要从后面追上 front,还差一格的时候,判定队列为满。
java代码示例:
class MyCircularQueue2 {
public int[] elem;
public int front;
public int rear;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue2(int k) {
this.elem = new int[k];
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
public boolean insertFront(int value) {
if(isFull()) {
return