题目:输入两个整数序列。其中一个序列表示栈的push 顺序,
判断另一个序列有没有可能是对应的pop 顺序。
思路:首先新建一个栈。从push序列开始遍历,如果当前元素与pop序列当前元素相等,则两个序列向前推进。
否则如果当前栈的栈顶元素与与pop序列当前元素相等,则pop序列向前推进,栈顶元素出栈。
否则如果当前push序列还没遍历完,则将push序列当前元素压入栈,然后继续迭代。
否则返回push与pop序列不对应的信息。
在找到所有匹配之后,返回true。
- 01.#include<iostream>
- 02.#include<stack>
- 03.using namespace std;
- 04.
- 05.bool isPopSequence(const int pushArry[],const int popArry[],int _size)
- 06.{
- 07. const int* pPush=pushArry;
- 08. const int* pPop=popArry;
- 09. stack<int> stData;
- 10. int cnt=0;
- 11. while(pPop-popArry<_size) //判断是否已经遍历完
- 12. {
- 13. if(pPush-pushArry>=_size&&stData.empty())break;
- 14.
- 15. if(pPush-pushArry<_size&&*pPush==*pPop){ // pushArry当前元素与popArry当前元素相等
- 16. pPush++;
- 17. pPop++;
- 18. }
- 19. else if(!stData.empty()&&stData.top()==*pPop){ //栈顶元素与popArry当前元素相等
- 20. stData.pop();
- 21. pPop++;
- 22. }
- 23. else if(pPush-pushArry<_size){ //如果pushArry还没遍历完
- 24. stData.push(*pPush);
- 25. pPush++;
- 26. }
- 27. else return false; //找不到匹配值
- 28. }
- 29. return true;
- 30.}
- 31.
- 32.
- 33.int main()
- 34.{
- 35.
- 36. int a[5]={1,2,3,4,5};
- 37. int b[5]={2,5,4,3,1};
- 38. cout<<isPopSequence(a,b,5)<<endl;
- 39.
- 40. return 0;
- 41.}