题目描述
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
解题思路
这道题说“循环”的意思是要求我们在数组里实现。使用链表的实现,创建结点和删除结点都是动态的,也就不存在需要循环利用的问题了。
-
在数组里的操作,我们参考“动态数组”的实现来完成,主要是为了让每一步的操作复杂度都最低。只不过不要求我们实现动态扩容与缩容。本题我们需要注意的地方有:
-
定义循环变量
front
和rear
。一直保持这个定义,到底是先赋值还是先移动指针就很容易想清楚了。front
:指向队列头部第1
个有效数据的位置;rear
:指向队列尾部(即最后1
个有效数据)的下一个位置,即下一个从队尾入队元素的位置。
(说明:这个定义是依据“动态数组”的定义模仿而来的)
-
为了避免“队列为空”和“队列为满”的判别条件冲突,我们有意浪费了一个位置。
浪费一个位置是指:循环数组中任何时刻一定至少有一个位置不存放有效元素。
- 判别队列为空的条件是:
front == rear;
- 判别队列为满的条件是:
(rear + 1) % capacity == front;
。可以这样理解:当rear
循环到数组的前面,要从后面追上front
,还差一格的时候,即判定队列为满。
- 判别队列为空的条件是:
-
因为有循环的出现,要特别注意处理数组下标可能越界的情况。
- 指针后移的时候,索引
+1
,所以要注意取模。
- 指针后移的时候,索引
-
参考代码
这道题是2019年计算机考研408专业课最后一道算法题。
class MyCircularQueue {
private:
vector<int> arr;
int front;
int rear;
int capacity;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
capacity = k + 1;
arr.assign(capacity, 0); // 要多分配一个位置的空间才行
front = 0;
rear = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if (isFull()) {
return false;
}
arr[rear] = value;
rear = (rear + 1) % capacity;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if (isEmpty()) {
return false;
}
front = (front + 1) % capacity;
return true;
}
/** Get the front item from the queue. */
int Front() {
if (isEmpty()) {
return -1;
}
return arr[front];
}
/** Get the last item from the queue. */
int Rear() {
if (isEmpty()) {
return -1;
}
return arr[(rear - 1 + capacity) % capacity]; // 注:循环队列的长度为 (rear - front + capacity) % capacity
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return front == rear;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
// 注意:这是这个经典设计的原因
return (rear + 1) % capacity == front;
}
};