栈的push、pop序列

来源:互联网 发布:天天向上网络作家专场 编辑:程序博客网 时间:2024/05/02 00:25

题目:输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。为了简单起见,我们假设push序列的任意两个整数都是不相等的。 

比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。因为可以有如下的push和pop序列:push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,这样得到的pop序列就是4、5、3、2、1。但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。

模拟解之~判断栈顶元素与pop元素是否相等,不等则push,相等则出栈,继续比较栈顶元素与pop元素。代码如下:

view sourceprint?
01//栈的push、pop序列
02#include<iostream>
03#include<stack>
04const int SIZE=5;                  //定义长度
05using namespace std;
06bool judge(int Spush[],int Spop[]){
07    stack<int> my_stack;
08    int iPush=0,iPop=0;
09    while(iPush<SIZE){                //当栈顶和pop相等时,将pop后的栈顶与pop之后的元素相比,直到不等
10        cout<<"push "<<Spush[iPush]<<endl;         //测试
11        my_stack.push(Spush[iPush]);
12        while(!my_stack.empty()&&iPop!=5&&my_stack.top()==Spop[iPop]){  //小心数组越界
13            cout<<"pop "<<Spop[iPop]<<endl;      //测试
14            iPop++;
15            my_stack.pop();
16        }
17        iPush++;
18    }
19    if(iPop==SIZE) return true;
20    else return false;
21}
22int main(void){
23    int Spush[SIZE],Spop[SIZE];
24    for(int i=0;i<SIZE;i++)
25        cin>>Spush[i];
26    for(int i=0;i<SIZE;i++)
27        cin>>Spop[i];
28    if(judge(Spush,Spop)) cout<<"Yes"<<endl;
29    else cout<<"No"<<endl;
30    system("pause");
31    return 0;
32}

原创粉丝点击