Can anyone tell me why this(if else) is not working? Thanks!


  • 0
    C

    This is my accepted code.

    Stack<Integer> stack = new Stack<Integer>();
    int min = Integer.MAX_VALUE ;
    
    public MinStack() {}
    
    public void push(int x) {
        if(x <= min) {
            stack.push(min);
            min = x;
        }
        stack.push(x);
    }
    
    public void pop() {
        if (stack.empty()) min = Integer.MAX_VALUE;
       
        if (stack.peek() == min){
            stack.pop();
            min = stack.peek();
            stack.pop();
        }
        else stack.pop();    
    }
    
    public int top() {
        return stack.peek(); 
    }
    
    public int getMin() {
        return min;  
    }
    

    for my pop method if I write like this it is not working, can anyone tell me why? Thanks

    public void pop() {
        if (stack.empty()) min = Integer.MAX_VALUE;
       
        if (stack.peek() == min){
            stack.pop();
            min = stack.peek();
        }
        stack.pop();

Log in to reply
 

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