C++的STL 栈实现 判断栈的出栈顺序是否合理
生活随笔
收集整理的這篇文章主要介紹了
C++的STL 栈实现 判断栈的出栈顺序是否合理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有這樣的題目:
已知從1至n的數字序列,按順序入棧,每個數字入棧后即可出棧, 也可在棧中停留,等待后面的數字入棧出棧后,該數字再出棧,求該數字序列的出棧序列是否合法?
類似如下:
已知棧的出棧序列為:3 2 5 4 1,判斷該棧的出棧序列是否合法
過程如下:
第一次1-5順序入棧:1,2,3
第二次 3 出棧:1,2
第三次 2 出棧:2
第四次 4,5 入棧:1,4,5
第五次 5 出棧:1,4
第六次 4 出棧:1
第七次 1 出棧:
最終可以得到合法的出棧序列:3 2 5 4 1
而序列:3 1 2 4 5 則不合法
解決方法主要是使用棧和隊列來模擬整個過程,是否滿足
- 出棧序列存放在隊列中:3,2,5,4,1,創建一個臨時棧來存放入棧序列(1-5)
- 模擬入棧過程,同時判斷入棧后的棧頂是否和隊列的對頭是否相等;相等則意味著此時該數值合理出棧;否則繼續入棧
- 上過程結束后,若臨時棧或者隊列中仍然存在元素,則該出棧序列不合法
具體過程如下:
初始:
queue: 3 2 5 4 1
stack:
第一次:3 2 5 4 1
stack:1
第二次:
queue: 3 2 5 4 1
stack: 1,2
第三次:
queue: 2 5 4 1
stack: 1,2
第四次:
queue 2 5 4 1
stack: 1,2,4
…
最后一次:
queue: 1
stack :1
實現代碼如下:
bool judge_formal_seq(queue<int> order){stack<int> seq;int num = order.size();if (order.empty()) {return false;}for (int i = 1; i <= 5; ++i) {seq.push(i);/*判讀隊頭元素和棧頂元素是否相等,相等則認為該元素可以出棧,兩者都pop*/while (!seq.empty() && order.front() == seq.top()) { order.pop();seq.pop();}}if(seq.empty()) {return true;} else {return false;}
}
測試代碼如下:
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>using namespace std;bool judge_formal_seq(queue<int> order){stack<int> seq;int num = order.size();if (order.empty()) {return false;}for (int i = 1; i <= 5; ++i) {seq.push(i);while (!seq.empty() && order.front() == seq.top()) {order.pop();seq.pop();}}if(seq.empty()) {return true;} else {return false;}
}int main() {queue<int> order;int tmp;cout << "construct the exit stack seq :" << endl;for (int i = 0; i < 5; ++i){cin >> tmp;order.push(tmp);}cout << "judge the stack seq is " << (judge_formal_seq(order)?"true":"false") << endl;return 0;
}
輸出如下:
construct the exit stack seq :
3 2 5 4 1
judge the stack seq is trueconstruct the exit stack seq :
3 1 2 5 4
judge the stack seq is false
總結
以上是生活随笔為你收集整理的C++的STL 栈实现 判断栈的出栈顺序是否合理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 输卵管堵塞对生育有影响
- 下一篇: C++的STL 栈 实现四则运算