javastacklifo

stack.pop() inside of if statement


I am wondering if calling the pop() method from the Stack data structure within an if statement will pop off the first element from the stack?

Here is an example of code:

public void pop() {
    if(stack.pop() == min) min=stack.pop();
}

Will this work? Or is it better to declare it like so:

public void pop() {
    int poppedOff = stack.pop();
    if(poppedOff == min) min=stack.pop();
}

I am assuming these are doing the same things but I am not completely sure.


Solution

  • Yes. It will, every invocation of pop will pop an element off the stack. Use peek() or save the value when you call pop() (like your second example). Also, setting min to the value when it equals the value is pointless.