思路:根据弹出序列的顺序确定哪些元素已入栈。栈为空或是栈顶元素与弹出序列不一致,则将压入序列的元素入栈直到和栈顶元素和弹出序列相当等。大循环终止条件while(indexPop<length)
函数接口: bool IsPopOrder(int*pushArray,int*popArray,int length);
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<stack>
using namespace std;
//面试题22栈的压入弹出序列 思路:根据弹出序列的顺序确定哪些元素已入栈。栈为空或是栈顶元素与弹出序列不一致,则将压入序列的元素入栈直到和栈顶元素和弹出序列相当等。大循环终止条件while(indexPop<length)
bool IsPopOrder(int * pushArray,int* popArray,int length)
{
if(pushArray!=NULL&&popArray!=NULL&&length>0)
{
stack<int>Stack;
int indexPush=0,indexPop=0;
while(indexPop<length)
{
while(Stack.empty()||Stack.top()!=popArray[indexPop])//栈为空或栈顶元素不为弹出序列的的值
{
if(indexPush>=length)
{
break;//此处break 比较关键
}
Stack.push(pushArray[indexPush]);
indexPush++;
}
if(Stack.top()!=popArray[indexPop])
{
break;
}
Stack.pop();
indexPop++;
}
if(Stack.empty()&&indexPop>=length)
{
return true;
}
}
return false;
}
int main()
{
int pushArray[]={1,2,3,4,5};
int popArray[]={4,5,3,2,1};
int length=sizeof(pushArray)/sizeof(pushArray[0]);
if(IsPopOrder(pushArray,popArray,length))
{
cout<<"是栈的压入弹出序列"<<endl;
}
else
{
cout<<"不是栈的压入弹出序列"<<endl;
}
return 0;
}