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

class MinStack {
     public class Node
        {
            int value;
            int min;
            Node next;
            public Node(int value,int min)
            {
                this.value = value;
                this.min = min;
                next = null;
            }
        }
        Node head;
        public void push(int x) {
            if(null==head)
            {
                head = new Node(x,x);
            }
            else
            {
                Node n = new Node(x,Math.min(x, head.min));
                n.next = head;
                head = n;
            }

        }

        public void pop() {
            if(head!=null)
                head = head.next;

        }

        public int top() {
            if(head!=null)
                return head.value;
            return -1;
        }

        public int getMin() {
            if(null!=head)
                return head.min;
            return -1;
        }
    }


你可能感兴趣的:(LeetCode)