栈的相关程序题

面试题:栈的压入、弹出序列
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列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;
}
}

posted @ 2014-03-27 21:34  zhoudan  阅读(260)  评论(0编辑  收藏  举报