29.栈的push、pop序列
2013-02-23 17:08
281 查看
题目:输入两个整数序列。其中一个序列表示栈的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序列。
答案:
//20130223
判断另一个序列有没有可能是对应的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序列。
答案:
//20130223
#include <iostream> #include <stack> using namespace std; bool pushOrder(int const pushs[], int const pops[], int n); int main() { int a[5] = {1, 2, 3, 4, 5}; int b[5] = {4, 5, 3, 2, 1}; bool c = pushOrder(a, b, 5); return 0; } bool pushOrder(int const pushs[], int const pops[], int n) { int i; stack<int> si; int j = 0; for (i = 0; i < n;) { while (j != n) { if (si.size() == 0) { si.push(pushs[j++]); if (pops[i] == si.top()) { si.pop(); ++i; break; } } else { if (pops[i] == si.top()) { si.pop(); ++i; break; } else { si.push(pushs[j++]); } } } if (j == n) { if (pops[i++] == si.top()) { si.pop(); } else { break; } } } if (i == n) { return true; } else { return false; } }
相关文章推荐
- 29.栈的push、pop序列(栈)
- 29. 栈的push,pop序列
- 29.栈的push、pop 序列
- 栈的push、pop序列(29)
- 29 栈的 push、pop 序列
- 29.栈的push、pop 序列
- Q29、栈的 push、pop 序列(栈)
- 29、栈的push、pop序列
- 微软面试100题之29题:栈的push、pop 序列
- 算法习题29:栈的push、pop序列是否一致
- 29.栈的push、pop 序列
- 微软面试100题-栈的push-pop序列问题
- 每天一道算法题(11)——栈的push、pop 序列
- 栈的push、pop序列
- 栈的push、pop序列
- 栈的push、pop序列
- 程序员面试题精选100题(24)-栈的push、pop序列
- 栈的push、pop序列
- 24.栈的push和pop序列[StackPushPopSequence]
- 每天一道算法题(11)——栈的push、pop 序列