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

来源:互联网 发布:淘宝steam喜加一哪个好 编辑:程序博客网 时间:2024/05/21 11:34

输入两个整数序列。其中一个序列表示栈的push 顺序,判断另一个序列有没有可能是对应的pop 顺序。
为了简单起见,我们假设push 序列的任意两个整数都是不相等的。
比如输入的push 序列是1、2、3、4、5,那么4、5、3、2、1 就有可能是一个pop 系列,但序列4、3、5、1、2 就不可能是push 序列1、2、3、4、5 的pop 序列。

思路:

1.首先新建一个栈模拟入栈入栈,都是在push序列中进行。

2.将push序列依次开始入栈,直到栈顶元素等于pop序列的第一个元素。

3.push的栈顶元素出栈,pop序列移到第二元素。

4.如果push栈顶继续等于pop序列现在的元素,则继续出栈并pop后移。

5.如果push已经全部入栈但是pop序列未遍历结束,且栈顶元素不等于现在所指元素则返回false。

6.如果栈为空,且pop也已经遍历结束,则返回true
按照上述思路,给出了源代码:代码中有两个实现,其中第一个是按照原作者的思路实现的,另外一个是网上的答案。

#include <iostream>#include <stack>using namespace std;bool isPopSerial(int push[], int pop[], int n)//原作者自己写的一种方法,注意函数名{int i=0,j=0;stack<int> mystack;while(i < n)//只要没有全部将push数组push到栈中{mystack.push(push[i]);i++;while(!mystack.empty() && mystack.top() == pop[j]){mystack.pop();j++;}}if( mystack.empty() && j==n)//最后是pop序列的唯一条件:栈变空了,且pop序列游标到了最后return true;return false;//除此之外都不是pop序列}bool isPopSeries(int push[],int pop[],int length)//网上流传的经典答案{if(!push||!pop||length<=0)return false;stack<int> temp;int pushNum=0;int i = 0;while(i < length){while(temp.empty()||temp.top()!=pop[i]){if(pushNum < length)temp.push(push[pushNum++]);elsereturn false;}if(!temp.empty()&&temp.top()==pop[i]){temp.pop();i++;}}return true;}int main(){int pushArray[5] = {1,2,3,4,5};  int popArray[5] = {4,5,3,2,1};if(isPopSerial(pushArray,popArray,5))cout<<"yes"<<endl;elsecout<<"no"<<endl;return 0; }