Simple solution using custom stack


  • 0
    A

    Just create your own stack using a "linked list" type node structure.

    public class MinStack {
    
        /** initialize your data structure here. */
        
        private static class Node{
            private int val;
            private Node next;
            private int block_min; 
            
            public Node(int val){
                this.val = val;
            }
        }
        
        private Node top;
        
        public MinStack() {
            top = null;
        }
        
        public void push(int x) {
            if(top == null){
                top = new Node(x);
                top.block_min = x;
            }
            else{
                int prev_submin = top.block_min;
                Node newNode = new Node(x);
                newNode.next = top;
                top = newNode;
                top.block_min = Math.min(x, prev_submin);
            }
            
        }
        
        public void pop() {
           if (top == null) return;
           //int item = top.val;
           top = top.next;
           
        }
        
        public int top() {
            //if (top == null) return null;
            int item = top.val;
            return item;
        }
        
        public int getMin() {
            return top.block_min;
        }
    }
    

Log in to reply
 

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