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

来源:互联网 发布:淘宝买了个单机版 编辑:程序博客网 时间:2024/05/05 00:26
题目:输入两个整数序列。其中一个序列表示栈的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;}

0 0
原创粉丝点击