為了實(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;
}
}