栈的压入与弹出

题目描述:输入两个序列,一个为压入的序列,一个为弹出的序列。检查这两个序列是否符合栈的压入和弹出的性质。

算法实现:

 1 #include<iostream>
 2 #include<stack>
 3 using namespace std;
 4 
 5 bool IsPopOrder(const int *Push, const int *Pop, int nLength){
 6     bool tags = false;
 7     
 8     if(Push != NULL && Pop != NULL && nLength > 0){
 9         const int *tmpPush = Push;
10         const int *tmpPop = Pop;
11         
12         stack<int> stackData;
13         
14         while(tmpPop - Pop < nLength){
15             while(stackData.empty() || stackData.top() != *tmpPop){      //辅助栈非空,辅助栈的栈顶不等于下一个弹出的元素 
16                 if(tmpPush - Push == nLength){
17                     break;
18                 }
19                 
20                 stackData.push(*tmpPush);       //压入辅助栈 
21                 tmpPush++;
22             }
23             
24             if(stackData.top() != *tmpPop){
25                 break;
26             }
27             
28             stackData.pop();          //弹出辅助栈的栈顶元素 
29             tmpPop++;
30         }
31         
32         if(stackData.empty() && tmpPop - Pop == nLength){
33             tags = true;
34         }
35     }
36     
37     return tags;
38 } 
39 
40 int main(){
41     int pPush[] = {1, 2, 3, 4, 5};
42     int pPop[] = {5, 4, 3, 2 ,1};
43     int len = sizeof (pPush) / sizeof(int);
44     bool result = IsPopOrder(pPush, pPop, len);
45     if(result == true){
46         cout<<"true order"<<endl;
47     }
48     else{
49         cout<<"wrong order"<<endl;
50     }
51     return 0;
52 }

  参考书籍:

《剑指offer》

posted @ 2016-04-10 16:28  Dormant  阅读(419)  评论(0编辑  收藏  举报