Solution using a Linked List. Clean and self-explanatory.


  • 4
    C
    class MinStack {
        class Node{
        int value;
        int min;
        Node next=null;
            Node(int x, int min){
                value=x;
                this.min=min;
            }
        }
        Node head=null;
        public void push(int x) {
            if(head ==null){
                head = new Node(x,x);
            }else{
                Node n = new Node(x, Math.min(head.min,x));
                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(head!=null)
                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.