155. 最小栈

2019-02-18  本文已影响0人  上杉丶零
class MinStack {
    private Stack<Integer> stackData = new Stack<Integer>();
    private Stack<Integer> stackMin = new Stack<Integer>();

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

        if (stackMin.isEmpty() || x < stackMin.peek()) {
            stackMin.push(x);
        } else {
            stackMin.push(stackMin.peek());
        }
    }

    public void pop() {
        if (stackMin.isEmpty()) {
            throw new RuntimeException("栈为空");
        }

        stackMin.pop();
        stackData.pop();
    }

    public int top() {
        if (stackMin.isEmpty()) {
            throw new RuntimeException("栈为空");
        }

        return stackData.peek();
    }

    public int getMin() {
        if (stackMin.isEmpty()) {
            throw new RuntimeException("栈为空");
        }

        return stackMin.peek();
    }
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读