29.栈的push、pop 序列

题目:输入两个整数序列。其中一个序列表示栈的push 顺序,
判断另一个序列有没有可能是对应的pop 顺序。
为了简单起见,我们假设push 序列的任意两个整数都是不相等的。
比如输入的push 序列是1、2、3、4、5,那么4、5、3、2、1 就有可能是一个pop 系列。
因为可以有如下的push 和pop 序列:
push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,
这样得到的pop 序列就是4、5、3、2、1。

但序列4、3、5、1、2 就不可能是push 序列1、2、3、4、5 的pop 序列。



HANDWRITING:

bool sequence (int *push, int *pop, int size) {
	stack<int> s;
	int in = 0, out = 0;
	while (out != size) {
		if (!s.empty() && s.top() == pop[out]) {
			s.pop(); ++out;
		} else if (in != size) {
			s.push( push[in] ); ++in;
		} else {
			return false;
		}
	}
	return true;
}




ANSWER FROM:http://blog.csdn.net/v_july_v/article/details/6870251
This seems interesting. However, a quite straightforward and promising way is to actually build the stack and check whether the pop action can be achieved.

int isPopSeries(int push[], int pop[], int n) {
	stack<int> helper;
	int i1=0, i2=0;
	while (i2 < n) {
		while (stack.empty() || stack.peek() != pop[i2]) {
			if (i1<n) 
				stack.push(push[i1++]);
			else
				 return 0;
			while (!stack.empty() && stack.peek() == pop[i2]) {
				stack.pop(); i2++;
			}
		}
	}
	return 1;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值