栈的压入、弹出序列
2013-07-22 21:25
141 查看
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
需要辅助栈,规律:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下一个弹出的数字不在栈顶,我们把压栈序列中还没有入栈数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。如果所有的数字都压入栈仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。
需要辅助栈,规律:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下一个弹出的数字不在栈顶,我们把压栈序列中还没有入栈数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。如果所有的数字都压入栈仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。
// Type your C++ code and click the "Run Code" button! // Your code output will be shown on the left. // Click on the "Show input" button to enter input data to be read (from stdin). #include <iostream> #include<stack> using namespace std; bool isPop0rder( const int *pPush, const int *pPop, const int length ) { if( pPush != NULL && pPop != NULL && length > 0 ) { stack< int > s; for( int i = 0,j=0; i < length; i++ ) { while( s.empty() || s.top() != pPop[i] ) { if( j == length ) { break; } s.push(pPush[j++]); } if( s.top() != pPop[i]) { return false; } s.pop(); } return true; } return false; } int main() { // Start typing your code here... cout << "Hello world!" << endl; int push[5]={1,2,3,4,5}; int pop[5]={4,5,3,1,2}; cout<<isPop0rder(push,pop,5); return 0; }
相关文章推荐
- 剑指offer 栈的压入、弹出序列
- 面试题 22: 栈的压入,弹出序列
- 面试题26:栈的压入、弹出序列
- 面试算法(二十一)栈的压入、弹出序列
- 牛客《剑指Offer》栈的压入、弹出序列
- 《剑指offer》面试题22—栈的压入、弹出序列
- 剑指Offer学习总结-栈的压入、 弹出序列
- 【剑指offer】4.3举例让抽象问题具体化——面试题22:栈的压入、弹出序列
- 面试题22 栈的压入、弹出序列
- 栈的压入、弹出序列
- 剑指Offer:栈的压入、弹出序列(JAVA)
- 21.栈的压入、弹出序列
- 剑指offer代码解析——面试题22栈的压入、弹出序列
- 剑指offer--栈的压入、弹出序列
- 栈的压入、弹出序列
- 栈的压入,弹出序列
- 栈的压入、弹出序列
- 剑指offer22:栈的压入、弹出序列
- 牛客网刷题之栈的压入、弹出序列
- 剑指 offer set 10 栈的压入、弹出序列