題目:輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否可能爲該棧的彈出順序。假設壓入棧的全部數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不多是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)ios
分析:以壓入1,2,3,4,5,彈出4,5,3,2,1爲例,首先壓入與彈出序列用vector執行,接受須要stack(先進後出),每壓入一個元素都須要與與彈出序列判等,若是相等直接pop(),不然繼續壓入,而判等條件s.top() == popV[j],判等次數須要一個循環while,退出條件就是壓入的全部元素都彈出了,即s.empty(),最後return s.empty();若是爲空,即彈出序列正確,不爲空,則彈出序列錯誤
數組
#include<iostream> using namespace std; #include<vector> #include<stack> class Solution { public: bool IsPopOrder(vector<int> pushV, vector<int> popV) { stack<int> s; int j = 0; for (int i = 0; i<pushV.size(); i++) { s.push(pushV[i]); while (!s.empty() && s.top() == popV[j]) { s.pop(); j++; } } return s.empty(); } }; int main()//測試 { //用數組給vector提供測試用例 /*int a[] = { 1, 2, 3, 4, 5 }; vector<int> pushV(a, a + 5); int b[] = { 4, 5, 3, 2, 1 }; vector<int> popV(b, b + 5);*/ //直接用vector容器 vector<int> v1{ 1, 2, 3, 4, 5 }; vector<int> v2{4,5,3,2,1}; Solution S; if (S.IsPopOrder(v1, v2)) cout << "True" << endl; else cout << "Flase" << endl; cout << "Hello world!" << endl; return 0; }