设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

    • push(x) —— 将元素 x 推入栈中。
    • pop() —— 删除栈顶的元素。
    • top() —— 获取栈顶元素。
    • getMin() —— 检索栈中的最小元素。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/min-stack


    1. class MinStack {
    2. Deque<Integer> xStack;
    3. Deque<Integer> minStack;
    4. public MinStack() {
    5. xStack = new LinkedList<Integer>();
    6. minStack = new LinkedList<Integer>();
    7. minStack.push(Integer.MAX_VALUE);
    8. }
    9. public void push(int x) {
    10. xStack.push(x);
    11. minStack.push(Math.min(minStack.peek(), x));
    12. }
    13. public void pop() {
    14. xStack.pop();
    15. minStack.pop();
    16. }
    17. public int top() {
    18. return xStack.peek();
    19. }
    20. public int getMin() {
    21. return minStack.peek();
    22. }
    23. }
    24. /**
    25. * Your MinStack object will be instantiated and called as such:
    26. * MinStack obj = new MinStack();
    27. * obj.push(x);
    28. * obj.pop();
    29. * int param_3 = obj.top();
    30. * int param_4 = obj.getMin();
    31. */