Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) — Push element x onto stack.
    • pop() — Removes the element on top of the stack.
    • top() — Get the top element.
    • getMin() — Retrieve the minimum element in the stack.

    Example:

    1. MinStack minStack = new MinStack();
    2. minStack.push(-2);
    3. minStack.push(0);
    4. minStack.push(-3);
    5. minStack.getMin(); --> Returns -3.
    6. minStack.pop();
    7. minStack.top(); --> Returns 0.
    8. minStack.getMin(); --> Returns -2.

    题意

    设计一个栈结构,在实现栈的基础功能之外,还需要实现一个获取当前栈最小值的方法,每个操作的时间复杂度要求为$O(1)$。

    思路

    维护两个栈来实现输出最小值:一个为普通栈stack,一个用于保存与当前普通栈中元素相对应的最小值栈minStack。push新元素x时,如果当前minStack为空,或者x值小于等于minStack栈顶元素,说明x是加入后普通栈中的最小值,需要在minStack入栈;pop栈顶元素x时,如果x与minStack栈顶元素相同,说明x正是当前普通栈中的最小值,也需要在minStack出栈。


    代码实现

    1. class MinStack {
    2. private LinkedList<Integer> stack;
    3. private LinkedList<Integer> minStack;
    4. /** initialize your data structure here. */
    5. public MinStack() {
    6. stack = new LinkedList<>();
    7. minStack = new LinkedList<>();
    8. }
    9. public void push(int x) {
    10. // 注意要使用<=,不然会引发NullPointerException
    11. if (minStack.isEmpty() || x <= minStack.peek()) {
    12. minStack.push(x);
    13. }
    14. stack.push(x);
    15. }
    16. public void pop() {
    17. int min = minStack.peek();
    18. if (stack.peek() == min) {
    19. minStack.pop();
    20. }
    21. stack.pop();
    22. }
    23. public int top() {
    24. return stack.peek();
    25. }
    26. public int getMin() {
    27. return minStack.peek();
    28. }
    29. }
    30. /**
    31. * Your MinStack object will be instantiated and called as such:
    32. * MinStack obj = new MinStack();
    33. * obj.push(x);
    34. * obj.pop();
    35. * int param_3 = obj.top();
    36. * int param_4 = obj.getMin();
    37. */