3

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
joshuar500
  • 164
  • 1
  • 15
  • 1
    Unless you can prove that when `min` is at the top of the stack there will ***always*** be another element on the stack, you run the risk of throwing an `EmptyStackException`. – Jim Garrison Nov 23 '17 at 00:08

1 Answers1

2

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249