zl程序教程

您现在的位置是:首页 >  其他

当前栏目

栈的压入、弹出序列_21

2023-04-18 16:10:28 时间

思路: 按照进栈顺序模拟出栈,看看最终栈里数据是否都能出去

public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer> stackA=new Stack();
        if (pushA.length==0||popA.length==0){
            return false;
        }

        int hasPopIndex=0;

        for (int item : pushA) {
            stackA.push(item);
            
            //如果栈不为空,且栈顶元素等于弹出序列
            while (!stackA.isEmpty()&&stackA.peek()==popA[hasPopIndex]){
                stackA.pop();
                hasPopIndex++;
            }
        }

        return stackA.isEmpty();
    }