日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

Leetcode 622. 设计循环队列 解题思路及C++实现

發布時間:2025/4/16 c/c++ 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode 622. 设计循环队列 解题思路及C++实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

解題思路:

使用整數數組來作為隊列的數據結構,設置兩個位置指針:front 和 end,front指向隊首元素,end指向隊尾的下一個元素(即為空位置)。當 front 和 end 相等時,有兩種情況:隊列為空 或 隊列滿了。這時候需要輔助的標記位 flag。當插入新元素時,要判斷隊列是否會變滿;當刪除元素的時候,要判斷隊列是否變為空。相應地更新flag。

?

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();*/

?

?

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的Leetcode 622. 设计循环队列 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。