6ms Java Solution using Linked List. Clean, self-explanatory and efficient.


  • 24
    C
    class MinStack {
        class Node{
            int value;
            int min;
            Node next;
            
            Node(int x, int min){
                this.value=x;
                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;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.