题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序
思路如下:pop的数字正好是栈顶数字,直接pop出栈即可;
如果希望pop的数字目前不在栈顶,我们就到
push序列中还没有被push到栈里的数字中去搜索这个数字,
并把在它之前的所有数字都push进栈。
如果所有的数字都被push进栈仍然没有找到这个数字,表明该序列不可能是一个pop序列。
代码如下:
#include<iostream>
#include<stack>
using namespace std;
stack<int> stackvolume;
bool PopOrder(int* Data,int *Poporder,int length)
{
int i = 0;
int datano = 0;
while(i < length)
{
if(!stackvolume.empty() && stackvolume.top() == Poporder[i])
stackvolume.pop();
else
{
while((datano < length) && (Data[datano] != Poporder[i]))
stackvolume.push(Data[datano++]);
if((datano == length) && (Data[datano - 1] != Poporder[i]))
return false;
}
i++;
}
return true;
}
int main()
{
int Data[] = {1,2,3};
int Poporder[] = {3,1,2};
int length = 3;
if(PopOrder(Data,Poporder,length))
cout<<"The Order may be the Order of Pop"<<endl;
else
cout<<"The Order is not the Order of Pop"<<endl;
return 0;
}

1721

被折叠的 条评论
为什么被折叠?



