栈的push、pop序列[数据结构]

题目:输入两个整数序列。其中一个序列表示栈的 push 顺序,判断另一个序列有没有可能是对应的 pop 顺序。为了简单起见,我们假设 push 序列的任意两个整数都是不相等的。

比如输入的push序列是12345,那么45321就有可能是一个pop系列。因为可以有如下的pushpop序列:push 1push 2push 3push 4poppush 5poppoppoppop,这样得到的pop序列就是45321。但序列43512就不可能是push序列12345pop序列。

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

bool isPossiblePopOrder(int *push, int *pop, int length){
	if(push && pop && length > 0){
		int *pNextPush = push;
		int *pNextPop = pop;
		stack<int> stackdata;
		bool isPossible = false;
		while(pNextPop - pop < length){
			while(stackdata.empty() || stackdata.top() != *pNextPop){
				if(!pNextPush){
					break;
				}
				stackdata.push(*pNextPush);
				if(pNextPush - push < length){
					pNextPush++;
				}else{
					pNextPush = NULL;
				}
			}
			if(stackdata.top() != *pNextPop){
				break;
			}
			stackdata.pop();
			pNextPop++;
		}
		if(stackdata.empty() && pNextPop - pop == length){
			isPossible = true;
		}
		return isPossible;
	}
}
int main(){
	int push[5] = {
		1, 2, 3, 4, 5
	};
	int pop[5] = {
		4, 3, 5, 1, 2
	};
	bool result = isPossiblePopOrder(push, pop, 5);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值