Java solution, 6 ms


  • -1
    W
    class MinStack {
        public class Node{
            Node next;
            int value;
            public Node(int value){
                this.value = value;
            }
        }
        private Node head;
        private Node minHead;
    
        public MinStack(){
            head = null;
            minHead = null;
        }
        public void push(int x) {
            Node node = new Node(x);
            if(head == null){
                head = node;
                minHead = new Node(x);
            }else{
                node.next = head;
                head = node;
                if(x <= minHead.value){
                    Node newMin = new Node(x);
                    newMin.next = minHead;
                    minHead = newMin;
                }
            }
        }
    
        public void pop() {
            if(head == null){
                return;
            }
            Node n = head;
            head = head.next;
            if(n.value == minHead.value){
                minHead = minHead.next;
            }
        }
    
        public int top() {
            if(head == null){
                return -1;
            }
            return head.value;
        }
    
        public int getMin() {
            if(minHead == null){
                return -1;
            }
            return minHead.value;
        }
    }

Log in to reply
 

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