1:输入一个压栈序列,判断第二个序列是否为其出栈序列。
例如:入栈序列:1 2 3 4 5 6,出栈序列,4,3,5,2,6,1
算法思想,1:根据出栈序列,入栈,直到其栈顶等于出栈元素,栈s:4,3,2,1
2:栈顶与出栈序列相同出栈,否则break
根据入栈序列入栈:(左为栈顶)
栈:1 2 3 4 1 2 3 1 2 5 1 2 1 6 1 |空
出栈元素: 4 3 5 2 6 1 , 4 3 5 2 6 1 ,4 35 2 6 1,4 3 5 2 6 1 ,4 3 5 26 1 ,4 3 5 2 61 ,完
#include <iostream>
#include <stack>
using namespace std;
bool IsStackPopOrder(int *pushorder,int *poporder,int len)
{
bool isorder = false;
if(pushorder!=NULL && poporder != NULL && len > 0)
{
stack<int> s;
int *pnextpush = pushorder;
int *pnextpop = poporder;
while((pnextpop - poporder) < len)
{
while(s.empty()||s.top()!=*pnextpop)
{
if((pnextpush - pushorder)==len)break;
s.push(*pnextpush);
pnextpush++;
}
if (s.top() == *pnextpop)
{
s.pop();
pnextpop++;
}
else break;
}
if ((pnextpop - poporder)==len && s.empty())isorder = true;
}
return isorder;
}
void main()
{
int array1[7] = {1,2,3,4,5,6,7};
int array2[7] = {4,3,5,6,7,1,2};
if(IsStackPopOrder(array1,array2,7))cout<<"是";
else cout<<"否";
system("pause");
}