【剑指offer 面试题22】栈的压入、弹出序列

思路:

  不停地压栈,直到栈头元素与弹出序列的首元素相等则出栈,同时弹出序列后移;若不相等则一直保持压栈,直到压入所有元素后弹出序列仍不为空,则说明无法匹配。

C++:

 1 #include <iostream>
 2 #include <vector>
 3 #include <stack>
 4 using namespace std;
 5 
 6 bool IsPreOrder(vector<int>& pushVec, vector<int>& popVec)
 7 {
 8     if(pushVec.size() != 0 && popVec.size() != 0)
 9     {
10         vector<int>::iterator itPush = pushVec.begin();
11         vector<int>::iterator itPop = popVec.begin();
12 
13         stack<int> _stack;
14 
15         while(itPop != popVec.end())
16         {
17             while(_stack.empty() || _stack.top() != *itPop)
18             {
19                 if(itPush == pushVec.end())
20                     break;
21 
22                 cout<<"push: "<<*itPush<<endl;
23                 _stack.push(*itPush);
24                 itPush++;
25             }
26 
27             if(_stack.top() != *itPop)
28                 break;
29 
30             cout<<"pop: "<<_stack.top()<<endl;
31             _stack.pop();
32             itPop++;
33         }
34 
35         if(_stack.empty() && itPop == popVec.end())
36             return true;
37     }
38     return false;
39 }
40 
41 int main()
42 {
43     int apush[] = {1,2,3,4,5};
44     int apop1[] = {4,5,3,2,1};
45     int apop2[] = {4,3,5,1,2};
46 
47     vector<int> vpush(apush, apush + 5);
48     vector<int> vpop1(apop1, apop1 + 5);
49     vector<int> vpop2(apop2, apop2 + 5);
50     cout<<"push: 1 2 3 4 5 pop: 4 5 3 2 1"<<endl;
51     cout<<"res = "<<IsPreOrder(vpush, vpop1)<<endl<<endl;
52     cout<<"push: 1 2 3 4 5 pop: 4 3 5 1 2"<<endl;
53     cout<<"res = "<<IsPreOrder(vpush, vpop2)<<endl;
54 }

 

测试结果:


push: 1 2 3 4 5 pop: 4 5 3 2 1
push: 1
push: 2
push: 3
push: 4
pop: 4
push: 5
pop: 5
pop: 3
pop: 2
pop: 1
res = 1


push: 1 2 3 4 5 pop: 4 3 5 1 2
push: 1
push: 2
push: 3
push: 4
pop: 4
pop: 3
push: 5
pop: 5
res = 0

 

 

posted @ 2015-07-06 22:17  tjuloading  阅读(139)  评论(0)    收藏  举报