题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不等。例如序列1、2、3、4、5是某栈的压栈序列,序列4、5、3、2、1是该压栈序列对应的一个弹出序列,但4、3、5、1、2就不是该压栈序列的弹出序列。
分析:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下一个弹出的数字不是栈顶,我们把压入序列中没有入栈的数字压入到辅助栈,直到把下一个需要弹出的数字压入栈顶为止。如果所有的数字都压入栈了仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。
package Stackqueue;
import java.util.Stack;
public class IsPopOrderMain {
public boolean isPopOder(int[] pPush, int[] pPop, int nlength) {
boolean bPossible = false;
if (pPop != null && pPush != null && nlength > 0) {
Stack<Integer> stack = new Stack<Integer>();
int pnextpush = 0;
int pnextpop = 0;
while (pnextpop < nlength) {
while (stack.empty() || stack.peek() != pPop[pnextpop]) {
if (pnextpush == nlength)
break;
stack.push(pPush[pnextpush]);
pnextpush&