面试题:栈的压入、弹出序列
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1、2、3、4、5是某栈的压栈序列,序列4、5、3、2、1是该压栈序列的弹出序列,但4、3、5、1、2就不可能是该压栈序列的弹出序列。

#include<iostream>
#include<vector>
#include<string>
#include<stack>
using namespace std;
void main()
{
char ch='Y';
while(ch=='Y'||ch=='y')
{
stack<char,vector<char>>s;
char a[100],b[100];
cout<<"请输入初始顺序"<<endl;
cin>>a;
cout<<"请输入判断的顺序"<<endl;
cin>>b;
int i=0,j=0;
while(i<strlen(a))
{

if(a[i]==b[j])
{
i++;
j++;
cout<<"无需进栈,直接消掉"<<a[i-1]<<endl;
}
else
{
s.push(a[i++]);
cout<<"无匹配,进栈 "<<s.top()<<endl;
}
while(!(s.empty())&&(s.top()==b[j]))
{
j++;
cout<<"与栈中的元素匹配,出栈的是"<<s.top()<<endl;
s.pop();
}
}
cout<<"j== "<<j<<endl;
if(j==strlen(a)) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
cout<<"是否继续,若继续,请输入(Y或y):";
cin>>ch;
}
}

相关文章:

  • 2021-12-08
  • 2022-12-23
  • 2021-07-16
  • 2021-10-06
  • 2022-02-02
  • 2021-05-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2022-02-07
  • 2021-12-16
  • 2021-11-03
  • 2021-10-13
相关资源
相似解决方案