已知栈的压入顺序,判断弹出顺序是否正确

已知栈的压入顺序,判断弹出顺序是否正确。

思路:

1、建立一个辅助栈

2、如果栈顶元素不等于弹出元素,则按顺序将压入序列的元素压入栈,直至栈顶元素等于弹出元素。(栈为空时的特殊操作)

3、弹出栈顶元素,更新弹出元素。

4、重复执行2、3直至,待处理的弹出序列为空。

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

bool check(const vector<int> &a, const vector<int> &b)
{
	stack<int> sta;
	int len1 = a.size();
	int len2 = b.size();
	if (len2 == 0) return true;
	if (len1 == 0) return false;
	int aindex = 0;
	int bindex = 0;

	while (bindex < len2)
	{

		if (sta.size() == 0)
		{
			sta.push(a[aindex]);
			aindex++;
		}
		while (aindex < len1)
		{
			if (sta.top() != b[bindex])
			{
				sta.push(a[aindex]);
				aindex++;
			}
			else
			{
				break;
			}
		}
		if (sta.top() != b[bindex]) return false;
		sta.pop();
		bindex++;
	}
	return true;
}

int main()
{
	vector<int> a = { 1, 2, 3, 4, 5 };
	vector<int> b = { 4, 5, 3, 2, 1 };
	vector<int> c = { 4, 3, 5, 1, 2 };
	cout << check(a, b);
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值