剑指 Offer 30. 包含min函数的栈

2021-08-12  本文已影响0人  上杉丶零
class MinStack {
    private Stack<Integer> aStack;
    private Stack<Integer> bStack;

    public MinStack() {
        aStack = new Stack<>();
        bStack = new Stack<>();
    }

    public void push(int x) {
        aStack.push(x);

        if (bStack.empty() || bStack.peek() >= x) {
            bStack.push(x);
        }
    }

    public void pop() {
        if (aStack.pop().equals(bStack.peek())) {
            bStack.pop();
        }
    }

    public int top() {
        return aStack.peek();
    }

    public int min() {
        return bStack.peek();
    }
}
image.png
上一篇下一篇

猜你喜欢

热点阅读