C++利用兩個(gè)棧實(shí)現(xiàn)隊(duì)列的方法
1. 基礎(chǔ)
隊(duì)列:先進(jìn)先出,即插入數(shù)據(jù)在隊(duì)尾進(jìn)行,刪除數(shù)據(jù)在隊(duì)頭進(jìn)行;
棧:后進(jìn)先出,即插入與刪除數(shù)據(jù)均在棧頂進(jìn)行。
2. 思路
兩個(gè)棧實(shí)現(xiàn)一個(gè)隊(duì)列的思想:用pushStack棧作為push數(shù)據(jù)的棧,用popStack棧作為pop數(shù)據(jù)的棧。
- 只要是對(duì)隊(duì)列進(jìn)行push操作,就將數(shù)據(jù)push入pushStack棧中。
- 要實(shí)現(xiàn)隊(duì)列的pop操作,有二點(diǎn)原則,如果popStack為空的話那么我們就將pushStack所有的元素放到popStack中,然后取popStack棧頂元素就是隊(duì)列的隊(duì)頭;如果popStack不為空的話,我們就直接獲取popStack的棧頂元素。
- 對(duì)于top操作來說和pop操作類似,只是最后一步不用pop了。

3. 代碼
#include <iostream>
#include <stack>
#include <exception>
template<class T> class MyQueue {
public:
void push(const T& num); // 入隊(duì)列
T pop(); // 出隊(duì)列
T top();
private:
std::stack<T> pushStack;
std::stack<T> popStack;
};
template<typename T>
void MyQueue<T>::push(const T& num) {
pushStack.push(num);
}
template<typename T>
T MyQueue<T>::pop() {
if (pushStack.empty() && popStack.empty()) { // 如果二個(gè)棧都為空
throw std::runtime_error("queue is empty");
} else if (popStack.empty()) { // 如果popStack為空,將pushStack全部元素倒popStack
while (!pushStack.empty()) {
T data = pushStack.top(); // 獲取pushStack棧頂元素
pushStack.pop(); // 出棧
popStack.push(data);
}
}
T data = popStack.top();
popStack.pop();
return data;
}
template<typename T>
T MyQueue<T>::top() {
if (pushStack.empty() && popStack.empty()) { // 如果二個(gè)棧都為空
throw std::runtime_error("queue is empty");
} else if (popStack.empty()) { // 如果popStack為空,將pushStack全部元素倒popStack
while (!pushStack.empty()) {
T data = pushStack.top(); // 獲取pushStack棧頂元素
pushStack.pop(); // 出棧
popStack.push(data);
}
} else { // 如果popStack不為空的話直接返回popStack棧頂
T data = popStack.top();
return data;
}
}
int main() {
MyQueue<int> myQueue1;
myQueue1.push(1);
myQueue1.push(2);
myQueue1.push(3);
myQueue1.push(4);
std::cout << "current pop is:" << myQueue1.pop() << std::endl;
std::cout << "current pop is:" << myQueue1.pop() << std::endl;
std::cout << "current pop is:" << myQueue1.pop() << std::endl;
std::cout << "current pop is:" << myQueue1.pop() << std::endl;
std::cout << "current pop is:" << myQueue1.pop() << std::endl;
return 0;
}
4. 參考文獻(xiàn)
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
C++11?關(guān)鍵字?const?使用小結(jié)
const大致意思是“我承諾不改變這個(gè)值”。主要用于說明接口,這樣在把變量傳入函數(shù)時(shí)就不必?fù)?dān)心變量會(huì)在函數(shù)內(nèi)被改變,本文給大家介紹C++11?關(guān)鍵字?const?使用小結(jié),感興趣的朋友一起看看吧2021-12-12

