栈的push和pop 序列

//思路:
//模拟栈, 让栈顶元素和pop序列比较,若相等则出栈, 若不等则入栈
//结果:若栈空,则是,非空则不是。

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

#define NSIZ 1200


int IsPushPop(int push[], int pop[], int n)
{
	int i = 0, j = 0;
	stack<int > st;
	st.push(push[i]);

	while(i++ < n)
	{
		while(!st.empty() && j < n)
		{
			if (st.top() == pop[j])
			{
				++j;
				st.pop();
			}
			else
			{
				break;
			}
		}
		if (i < n)
		{
			st.push(push[i]);
		}
	}

	return st.size() == 0? 1: 0;
}

int main()
{
	int push[] = {1,2 , 3, 4, 5};
	int pop[] = {4, 3, 5, 1, 2};
	int n = sizeof(push)/sizeof(push[0]);

	printf("%s\n", IsPushPop(push, pop, n) == 0?"NO":"YES");

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值