隊列-實(shí)現(xiàn)

為了實(shí)現(xiàn)隊列,我們可以使用動態(tài)數(shù)組和指向隊列頭部的索引。

如上所述,隊列應(yīng)支持兩種操作:入隊和出隊。入隊會向隊列追加一個新元素,而出隊會刪除第一個元素。 所以我們需要一個索引來指出起點(diǎn)。

#include <iostream>

class MyQueue {

? ? private:

? ? ? ? // store elements

? ? ? ? vector<int> data;? ? ?

? ? ? ? // a pointer to indicate the start position

? ? ? ? int p_start;? ? ? ? ? ?

? ? public:

? ? ? ? MyQueue() {p_start = 0;}

? ? ? ? /** Insert an element into the queue. Return true if the operation is successful. */

? ? ? ? bool enQueue(int x) {

? ? ? ? ? ? data.push_back(x);

? ? ? ? ? ? return true;

? ? ? ? }

? ? ? ? /** Delete an element from the queue. Return true if the operation is successful. */

? ? ? ? bool deQueue() {

? ? ? ? ? ? if (isEmpty()) {

? ? ? ? ? ? ? ? return false;

? ? ? ? ? ? }

? ? ? ? ? ? p_start++;

? ? ? ? ? ? return true;

? ? ? ? };

? ? ? ? /** Get the front item from the queue. */

? ? ? ? int Front() {

? ? ? ? ? ? return data[p_start];

? ? ? ? };

? ? ? ? /** Checks whether the queue is empty or not. */

? ? ? ? bool isEmpty()? {

? ? ? ? ? ? return p_start >= data.size();

? ? ? ? }

};

int main() {

? ? MyQueue q;

? ? q.enQueue(5);

? ? q.enQueue(3);

? ? if (!q.isEmpty()) {

? ? ? ? cout << q.Front() << endl;

? ? }

? ? q.deQueue();

? ? if (!q.isEmpty()) {

? ? ? ? cout << q.Front() << endl;

? ? }

? ? q.deQueue();

? ? if (!q.isEmpty()) {

? ? ? ? cout << q.Front() << endl;

? ? }

}


#包括<iostream>

MyQueue類{

私人:

//存儲元素

向量<int>數(shù)據(jù);

//指示起始位置的指針

內(nèi)部啟動;

公眾:

MyQueue(){p_start=0;}

/**將元素插入隊列。如果操作成功,則返回true。*/

布爾排隊(整數(shù)x){

數(shù)據(jù)。向后推(x);

返回真值;

}

/**從隊列中刪除元素。如果操作成功,則返回true。*/

布爾出列(){

如果(isEmpty()){

返回false;

}

pústart++;

返回真值;

};

/**從隊列中獲取前端項。*/

內(nèi)部前端(){

返回數(shù)據(jù)[p_start];

};

/**檢查隊列是否為空。*/

bool isEmpty(){

return p_start>=data.size();

}

};

int主(){

我的隊列q;

q、 排隊(5);

q、 排隊(3);

如果(!q、 isEmpty()){

無法<<q.Front()<<endl;

}

q、 出列();

如果(!q、 isEmpty()){

無法<<q.Front()<<endl;

}

q、 出列();

如果(!q、 isEmpty()){

無法<<q.Front()<<endl;

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容