1.题目要求:
示例:
MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
circularQueue.enQueue(1); // 返回 true
circularQueue.enQueue(2); // 返回 true
circularQueue.enQueue(3); // 返回 true
circularQueue.enQueue(4); // 返回 false,队列已满
circularQueue.Rear(); // 返回 3
circularQueue.isFull(); // 返回 true
circularQueue.deQueue(); // 返回 true
circularQueue.enQueue(4); // 返回 true
circularQueue.Rear(); // 返回 4
2.题目代码:
class MyCircularQueue {
public:int front;int rear;vector<int> queue;/初始化MyCircularQueue(int k) {queue.resize(k + 1);front = rear = 0;}//入队bool enQueue(int value) {if(isFull() == true){return false;}else{queue[rear] = value;rear = (rear + 1) % queue.size();return true;}}//出队bool deQueue() {if(isEmpty() == true){return false;}else{front = (front + 1) % queue.size();return true;}}//找到首元素的值int Front() {if(isEmpty() == true){return -1;}else{return queue[front];}}//找到末尾值int Rear() {if(isEmpty() == true){return -1;}else{if(rear == 0){return queue[queue.size() - 1];}return queue[rear - 1];}}//判断是否为空bool isEmpty() {if(front == rear){return true;}else{return false;}}//判断是否已满bool isFull() {if((rear + 1) % queue.size() == (front) % queue.size()){return true;}else{return false;}}
};/*** Your MyCircularQueue object will be instantiated and called as such:* MyCircularQueue* obj = new MyCircularQueue(k);* bool param_1 = obj->enQueue(value);* bool param_2 = obj->deQueue();* int param_3 = obj->Front();* int param_4 = obj->Rear();* bool param_5 = obj->isEmpty();* bool param_6 = obj->isFull();*/