問題
判斷一數字序列是否為這些數字入棧的一種出棧方式(前提:棧中的數字不重復)
例如
假設入棧的序列為:1 2 3 4 5
那么4 5 3 2 1為一種彈出序列, 4 3 5 1 2不是
思路
開辟一個輔助棧,模擬入棧出戰過程(假設pa為入棧序列,pb為出戰序列)
- pa中的元素依次壓入輔助棧
- 新壓入的元素與彈出序列的棧底相同,輔助棧彈出,同時pb向上移動
- 不相同了pa中的元素繼續入輔助棧
參考代碼
#include <iostream> #include <stack> using namespace std; bool IsPopOrder(const int *a, const int *b, int lena, int lenb) { if(lena != lenb || lena == 0) return false; bool rev = false; int pa = 0; int pb = 0; int *newa = new int[lena]; int top = -1; for(pa = 0; pa < lena; ++pa) { ++top; newa[top] = a[pa]; while(newa[top] == b[pb]) { --top; ++pb; } } if(top == -1) rev = true; delete []newa; return rev; } int main() { int a[] = {1, 2, 3, 4, 5}; int b[] = {4, 5, 3, 2, 1}; int c[] = {4, 3, 5, 1, 2}; int d[] = {4, 5, 9, 2, 1}; int lena = sizeof(a) / sizeof(int); int lenb = sizeof(b) / sizeof(int); int lenc = sizeof(c) / sizeof(int); int lend = sizeof(d) / sizeof(int); cout << IsPopOrder(a, b, lena, lenb) << endl; cout << IsPopOrder(a, c, lena, lenc) << endl; cout << IsPopOrder(a, d, lena, lend) << endl; }
結果
1
0
0