栈的push、pop序列[数据结构]
2015-05-19 16:09
260 查看
题目:输入两个整数序列。其中一个序列表示栈的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序列。
比如输入的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序列。
#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; }
相关文章推荐
- 程序员面试题精选100题(24)-栈的push、pop序列[数据结构]
- 程序员面试题精选100题(24)-栈的push、pop序列[数据结构]
- 数据结构练习(19)栈的push、pop序列
- 程序员面试题精选100题(24)-栈的push、pop序列[数据结构]
- 29、栈的push、pop序列
- 两个整数序列,其中一个序列表示栈的push顺序, 判断另一个序列有没有可能是对应的pop顺序。
- Q29、栈的 push、pop 序列(栈)
- 一个序列是否可能是push序列的pop序列
- 25. 微软面试题:栈的push、pop序列(栈)
- 24.栈的push和pop序列[StackPushPopSequence]
- 定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都是O(1)。
- 输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序
- 栈的push、pop 序列
- 输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。为了简单起见,我们假设push序列的任意两个整数都是不相等的。 比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。
- 一个序列是否可能是push序列的pop序列
- 栈的push、pop序列-判断序列是否是栈的pop顺序
- 29.栈的push、pop 序列
- 【数据结构】堆的实现(包括:默认成员函数,插元素push,删元素pop,访问根节点top,判空,大小)
- 微软面试100题 之24栈的push、pop序列
- 栈的push、pop序列