力扣622.设计循环队列
-
- 通过数组索引构建一个虚拟的首尾相连的环
- 当front = rear时 队列为空
- 当front = rear + 1时 队列为满 (最后一位不存)
cpp
class MyCircularQueue {
int front;
int rear;
int capacity;
vector<int> elements;
public:
MyCircularQueue(int k) {
//最后一位不存元素 多开一个
capacity = k+1;
elements = vector<int>(capacity);
rear = front = 0;
}
bool enQueue(int value) {
if(isFull())
return false;
elements[rear] = value;
rear = (rear + 1) % capacity;
return true;
}
bool deQueue() {
if(isEmpty())
return false;
front = (front + 1) % capacity;
return true;
}
int Front() {
if(isEmpty())
return -1;
return elements[front];
}
int Rear() {
if(isEmpty())
return -1;
return elements[(rear - 1 + capacity) % capacity];
}
bool isEmpty() {
return rear == front;
}
bool isFull() {
return ((rear + 1) % capacity) == front;
}
};