Java, easy solution without java built in data type


  • 0
    S

    public class MinStack {
        
        private int val;
        private int min;
        private MinStack pre = null;
        private MinStack tail = null;
    
        /** initialize your data structure here. */
        public MinStack() {
        }
        
        public void push(int x) {
            if (tail == null) {
                tail = new MinStack();
                tail.val = x;
                tail.min = x;
            } else {
                MinStack st = new MinStack();
                st.val = x;
                st.min = x < tail.min ? x : tail.min;
                st.pre = tail;
                tail = st;
            }
        }
        
        public void pop() {
            if (tail != null) {
                tail = tail.pre;
            }
        }
        
        public int top() {
            return tail.val;
        }
        
        public int getMin() {
            return tail.min;
        }
    }
    

Log in to reply
 

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