有這樣的題目:
已知從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 true
construct the exit stack seq :
3 1 2 5 4
judge the stack seq is false