[LeetCode155] Min Stack

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.

CC150 原题
class MinStack {
    Node top = null;
    public void push(int x) {
        if(top == null) {
            top = new Node(x);
            top.min = x;
        } else {
            Node temp = new Node(x);
            temp.next = top;
            temp.min = Math.min(x, top.min);
            top = temp;
        }
    }

    public void pop() {
        top = top.next;
        return;
    }

    public int top() {
        if(top != null)
            return top.val;
        else
            return 0;
    }

    public int getMin() {
        if(top != null)
            return top.min;
        else
            return 0;
    }
    
    class Node {
        int val;
        int min;
        Node next;
        public Node(int val) {
            this.val = val;
        }
    }
}


你可能感兴趣的:(stack)