Fork me on GitHub

栈的压入、弹出序列

【题目描述】

    输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

【代码实现】

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 bool IsPopOrder(vector<int> pushV, vector<int> popV) {
 7     if (pushV.size() == 0)
 8         return false;
 9     vector <int> vec;
10     for (int i = 0, j = 0; i < pushV.size(); i++)
11     {
12         vec.push_back(pushV[i]);//重新模拟最初的压栈过程
13         while (j < popV.size() && vec.back() == popV[j])
14         {
15             vec.pop_back();//重新模拟最初的出栈过程
16             j++;
17         }
18     }
19     //顺利模拟成功,元素应当全部弹出,返回为true,否则会有元素无法弹出,导致非空,返回为false
20     return vec.empty();
21 }
22 
23 int main(void)
24 {
25     vector<int> pushlist{1,2,3,4,5 };
26     vector<int> poplist{4,3,5,1,2 };
27     cout << IsPopOrder(pushlist, poplist) << endl;
28     system("pause");
29     return 0;
30 }

 

posted @ 2015-12-09 12:41  GeekerLou  阅读(238)  评论(0编辑  收藏  举报