155. 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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --
>
 Returns -3.
minStack.pop();
minStack.top();      --
>
 Returns 0.
minStack.getMin();   --
>
 Returns -2.

Solution

(1) Java

class MinStack {

    class Node {
        int val;
        Node minNode;
        public Node(int val) {
            this.val = val;
            minNode = this;
        }
    }

    private Deque<Node> stack = new LinkedList<Node>();

    /** initialize your data structure here. */
    public MinStack() {

    }

    public void push(int x) {
        Node node = new Node(x);
        if (stack.size() != 0) {
            Node top = stack.peek();
            if (top.minNode.val < x) {
                node.minNode = top.minNode;
            }           
        }
        stack.push(node);
    }

    public void pop() {
        if (stack.size() > 0) {
            stack.pop();
        }
    }

    public int top() {
        if (stack.size() > 0) {
            Node node = stack.peek();
            return node.val;
        }
        return -1;
    }

    public int getMin() {
        if (stack.size() > 0) {
            Node top = stack.peek();
            return top.minNode.val;
        }
        return -1;
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

(2) Python



(3) Scala



results matching ""

    No results matching ""