Leetcode 622. 设计循环队列 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 622. 设计循环队列 解题思路及C++实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
解題思路:
使用整數(shù)數(shù)組來作為隊列的數(shù)據(jù)結構,設置兩個位置指針:front 和 end,front指向隊首元素,end指向隊尾的下一個元素(即為空位置)。當 front 和 end 相等時,有兩種情況:隊列為空 或 隊列滿了。這時候需要輔助的標記位 flag。當插入新元素時,要判斷隊列是否會變滿;當刪除元素的時候,要判斷隊列是否變?yōu)榭铡O鄳馗耭lag。
?
class MyCircularQueue { public:int front = 0; //隊首指針int end = 0; //隊尾指針,指向隊尾的下一個元素int n = 0; //隊列大小int flag = 0; //用于標記隊列是否為空vector<int> que;/** Initialize your data structure here. Set the size of the queue to be k. */MyCircularQueue(int k) {n = k;//對列初始化for(int i = 0; i < k; i++){que.push_back(0);}}/** Insert an element into the circular queue. Return true if the operation is successful. */bool enQueue(int value) {if(flag == 0){ //空隊列que[end] = value;if(end == n - 1) end = 0; //更新隊尾的下一個元素else end++;flag = 1; //標記非空return true;}else{ //非空隊列,判斷隊列是否已滿if(front == end) return false;else{que[end] = value;if(end == n - 1) end = 0; //更新隊尾的下一個元素else end++;return true;}}}/** Delete an element from the circular queue. Return true if the operation is successful. */bool deQueue() {if(flag == 0){return false;}else{que[front] = 0; //清0if(front == n - 1) front = 0; //更新隊首指針else front++;if(front == end) flag = 0;return true;}}/** Get the front item from the queue. */int Front() {if(flag == 0) return -1;else return que[front];}/** Get the last item from the queue. */int Rear() {if(flag == 0) return -1;else{if(end == 0) return que[n-1];else return que[end - 1];}}/** Checks whether the circular queue is empty or not. */bool isEmpty() {if(flag == 0) return true;else return false;}/** Checks whether the circular queue is full or not. */bool isFull() {if(flag == 1 && front == end) 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();*/?
?
《新程序員》:云原生和全面數(shù)字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Leetcode 622. 设计循环队列 解题思路及C++实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 621. 任务调度器
- 下一篇: Leetcode 375. 猜数字大小