面试题 31 : 栈的压入、弹出序列

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

例如序列1,2,3,4,5是某 栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

(注意:这两个序列的长度 是相等的)

class Solution12 {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        boolean bool = false;
        Stack<Integer> stack=new Stack<Integer>();
        int pushIndex=0,popIndex=0;
        if(pushA!=null || popA!=null) {
            while(pushIndex < pushA.length){
                stack.push(pushA[pushIndex]);
                while(stack.peek()==popA[popIndex]){
                    stack.pop();
                    popIndex++;
                    if(popIndex==popA.length){
                        break;
                    }
                }
                pushIndex++;
            }
        }
        //按照上面的逻辑,所有入栈的都能出栈,说明popA是pushA的弹出序列
        if(stack.size()==0 && pushIndex==pushA.length){
            bool=true;
        }    
        return bool;
    }
}
原文地址:https://www.cnblogs.com/Allen-win/p/8745620.html