Java problem for stack pop


  • 1
    H
    public class MinStack {
        
        Stack<Integer> s,minS;
        /** initialize your data structure here. */
        public MinStack() {
            s =  new Stack<>();
            minS = new Stack<>();
        }
        
        public void push(int x) {
            s.push(x);
            if(!minS.isEmpty() && minS.peek() < x) return; 
            minS.push(x);
        }
        
        public void pop() {
            // int p = s.pop();
            // if (p == minS.peek()) minS.pop();
            if(s.pop() == minS.peek()) minS.pop();
        }
        
        public int top() {
            return s.peek();
        }
        
        public int getMin() {
            return minS.peek();
        }
    }
    

    In the method "pop", I don't know why this one

    if(s.pop() == minS.peek()) minS.pop();
    

    doesn't pass, but the comment one does

     int p = s.pop();
     if (p == minS.peek()) minS.pop();
    

    I feel like they are the same...
    Any Idea?


  • 0
    H

    @huaying2
    when you push(int x), you create two instance of Integer with the same value of x. One push to stack s and other push to stack minS. When you compare p == minS.peek() you compare the reference and not the value.
    It works if you change to p.equals(minS.peek()).


  • 0
    H

    @hieu.trinh got it! Thanks!


  • 0
    P

    @huaying2 one minor question: should the pop() has a return value, not void?


  • 0
    P

    @huaying2 two more improvement for your implementation:

    1. please reference to Stack<E> implementation and implement it as generic type.
    2. try to enforce thread-safe for the methods.

    I was asked thread-safe issue during a very important interview. Guess it would benefit you, too.


  • 0
    S

    @hieu.trinh don't understand here. Why is p a reference? Isn't it an integer as declared "int p"; And int is not mutable so not a reference.


  • 0
    H

    @Shilez_
    if you have
    int p = s.pop();
    p == minStack.pop() should work find.
    So, you are right.

    If you have
    Integer p = s.pop(); then it would be the case try to say.
    Thanks.


Log in to reply
 

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