Java solution using StackNode. Beats 90% of Solutions


  • 2
    public class MinStack {
    
        private class StackNode {
            private int data;
            private int min;
            private StackNode next;
            
            public StackNode(int data, int min) {
                this.data = data;
                this.min = min;
            }
        }  
    
        private StackNode top;
    
        /** initialize your data structure here. */
        public MinStack() {}
        
        public void push(int x) {
            if (top == null) {
                StackNode newTop = new StackNode(x, x);
                top = newTop;
            } else {
                StackNode newTop = new StackNode(x, Math.min(x, top.min));
                newTop.next = top;
                top = newTop;
            }
        }
        
        public void pop() {
            if (top == null) {
                return;
            } else {
                top = top.next;
            }
        }
        
        public int top() {
            return top.data;
        }
        
        public int getMin() {
            return top.min;
        }
    }
    

    Basically make each stack node keep track of a min element when you push onto a stack. If the new element is less than the min of the top element, set the min to be the same as the element. Otherwise, take the min of the top and set it to be the min of the new element as well.

    Cheers. Let's make America great again.


  • 0
    L

    @Donald-J.-Trump It's quit a smart solution!


  • 0

    @laqxs thank you!


  • 0
    D

    Make stack great again!


Log in to reply
 

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