第二十九题(判断pop序列是否和push序列对应)

29.栈的push、pop序列
题目:输入两个整数序列。其中一个序列表示栈的push顺序,

判断另一个序列有没有可能是对应的pop顺序。


分析:

想要判断pop序列是不是和push序列对应,只要按照push序列和pop序列指定的顺序完成push和pop操作,然后看栈能否恰好在push和pop操作都结束后到达空的状态,若能,返回true。

若pop顺序正确,pop序列中的每个元素在push过程中总会有位于栈顶的时候,若在push结束时pop序列中的元素未能找到和其相同的栈顶元素,说明pop顺序有误,返回false

代码:

#include<stack>
#include<iostream>
using namespace std;
namespace MS100P_29
{
	bool isPopOfPush(const int *pushSeq, const int *popSeq, int length)
	{
		stack<int> s;
		int i = 0, j = 0;
		while (i != length || !s.empty())
		{
			if (i != length&&s.empty())	s.push(pushSeq[i++]);
			while (s.top() != popSeq[j])
			{

				if (i == length)	return false;
				s.push(pushSeq[i++]);
			}
			s.pop();
			j++;
		}
		return true;
	}

	void test()
	{
		int pushSeq[] = { 1, 2, 3, 4, 5 };
		int popSeq1[] = { 1, 2, 5, 3, 4 };
		int popSeq2[] = { 2, 1, 3, 4, 5 };
		int popSeq3[] = { 5, 3, 1, 2, 5 };
		int popSeq4[] = { 5, 4, 3, 2, 1 };
		int popSeq5[] = { 4, 2, 3, 1, 5 };
		int popSeq6[] = { 3, 4, 2, 1, 5 };
		cout << isPopOfPush(pushSeq, popSeq1, 5) << endl;
		cout << isPopOfPush(pushSeq, popSeq2, 5) << endl;
		cout << isPopOfPush(pushSeq, popSeq3, 5) << endl;
		cout << isPopOfPush(pushSeq, popSeq4, 5) << endl;
		cout << isPopOfPush(pushSeq, popSeq5, 5) << endl;
		cout << isPopOfPush(pushSeq, popSeq6, 5) << endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	MS100P_29::test();
	return 0;
}
测试的几组数据都没有问题,但是不是很确定程序完全正确,如有错误,欢迎大家指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值