判断出栈序列是否正确

题目:输入两个整数序列。其中一个序列表示栈的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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值