题目:
输入两个整数序列,第一个序列表示栈的压入顺序,判断第二个序列是否是栈的弹出序列。
思路:
#include<iostream>
#include<stdlib.h>
#include<stack>
using namespace std;
bool test(int* a,int* a1,int len)
{
stack<int> s1;
int i=0;
int j=0;
while(j<len)
{
while(i<len)
{
if(a[i]==a1[j]||(!s1.empty()&&s1.top()==a1[j]))
{
break;
}
s1.push(a[i]);
i++;
}
if(a[i]==a1[j])
{
s1.push(a[i]);
i++;
}
if(s1.top()==a1[j])
{
s1.pop();
j++;
}
else
{
return false;
}
}
return true;
}
int main()
{
int a[]={1,2,3,4,5};
int a1[]={4,5,3,2,1};
int a2[]={4,3,5,1,2};
int a3[]={4,3,2,1,5};
int a4[]={1,2,3,4,5};
int a5[]={3,5,4,2,1};
int a6[]={4,5,2,3,1};
int len=sizeof(a)/sizeof(a[0]);
cout<<test(a,a1,len)<<endl;
cout<<test(a,a2,len)<<endl;
cout<<test(a,a3,len)<<endl;
cout<<test(a,a4,len)<<endl;
cout<<test(a,a5,len)<<endl;
cout<<test(a,a6,len)<<endl;
system("pause");
return 0;
}
转载于:https://blog.51cto.com/youngyoungla/1776016