您的位置:首页 > 其它

栈的压入、弹出序列

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: