栈的压入与弹出

本文介绍了一个用于检查两个序列是否符合栈的压入和弹出性质的算法。通过使用辅助栈,该算法能够验证给定的压入和弹出序列是否合理。文章提供了详细的C++实现代码,并引用了《剑指offer》作为参考。

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

算法实现:

 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》

转载于:https://www.cnblogs.com/dormant/p/5374451.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值