栈的push、pop序列

 

题目:输入两个整数序列。其中一个序列表示栈的push 顺序,
判断另一个序列有没有可能是对应的pop 顺序。

思路:首先新建一个栈。从push序列开始遍历,如果当前元素与pop序列当前元素相等,则两个序列向前推进。

否则如果当前栈的栈顶元素与与pop序列当前元素相等,则pop序列向前推进,栈顶元素出栈。

否则如果当前push序列还没遍历完,则将push序列当前元素压入栈,然后继续迭代。

否则返回push与pop序列不对应的信息。

在找到所有匹配之后,返回true。

  1. 01.#include<iostream>    
  2. 02.#include<stack>    
  3. 03.using namespace std;    
  4. 04.    
  5. 05.bool isPopSequence(const int pushArry[],const int popArry[],int _size)    
  6. 06.{    
  7. 07.    const  int* pPush=pushArry;    
  8. 08.    const int* pPop=popArry;    
  9. 09.    stack<int> stData;    
  10. 10.    int cnt=0;    
  11. 11.    while(pPop-popArry<_size)      //判断是否已经遍历完     
  12. 12.    {    
  13. 13.        if(pPush-pushArry>=_size&&stData.empty())break;    
  14. 14.    
  15. 15.        if(pPush-pushArry<_size&&*pPush==*pPop){      // pushArry当前元素与popArry当前元素相等     
  16. 16.            pPush++;    
  17. 17.            pPop++;    
  18. 18.        }    
  19. 19.        else if(!stData.empty()&&stData.top()==*pPop){  //栈顶元素与popArry当前元素相等     
  20. 20.            stData.pop();    
  21. 21.            pPop++;    
  22. 22.        }    
  23. 23.        else if(pPush-pushArry<_size){            //如果pushArry还没遍历完     
  24. 24.            stData.push(*pPush);    
  25. 25.            pPush++;    
  26. 26.        }    
  27. 27.        else return false;      //找不到匹配值     
  28. 28.    }    
  29. 29.    return true;    
  30. 30.}    
  31. 31.    
  32. 32.    
  33. 33.int main()    
  34. 34.{    
  35. 35.    
  36. 36.    int a[5]={1,2,3,4,5};    
  37. 37.    int b[5]={2,5,4,3,1};    
  38. 38.    cout<<isPopSequence(a,b,5)<<endl;    
  39. 39.    
  40. 40.    return 0;    
  41. 41.}    
  42.   

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值