栈的压入、弹出序列

来源:互联网 发布:head first python 2 编辑:程序博客网 时间:2024/06/05 16:52

题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列。假设压入栈的所有数字均不相等。

解答:利用辅助栈的方式,首先建立两个栈,A栈用来表示栈的压入顺序,B栈表示栈的弹出顺序。将入栈的元素依次压入A栈中直到遇到与B栈栈顶元素相等,同时弹出A,B两栈的栈顶元素。如果入栈元素已全部进入A栈,但是B仍未全部弹出,则该序列不可能为弹出序列。

bool IsPopOrder(const int* pPush,const int* pPop,const int len){stack<int> pushStack;stack<int> popStack;for(int index = len - 1; index >= 0; --index)popStack.push(pPop[index]);int pushIndex = 0;while(!popStack.empty()){while(pushIndex != len){if(pushStack.empty()){pushStack.push(pPush[pushIndex++]);}else if(pushStack.top() != popStack.top())pushStack.push(pPush[pushIndex++]);elsebreak;}if(pushStack.top() == popStack.top()){pushStack.pop();popStack.pop();}else if(pushIndex == len)return false;}return true;}

0 0
原创粉丝点击