力扣622.设计循环队列
力扣622.设计循环队列
-
- 通过数组索引构建一个虚拟的首尾相连的环
- 当front = rear时 队列为空
- 当front = rear + 1时 队列为满 (最后一位不存)
-
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; } };
原文地址:https://blog.csdn.net/Pisasama/article/details/140504691
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!