awelgorithms

Reject pop from empty

Updated

Pop on [] is an error (or a defined empty result, not a fake value). Returning 0 or null-as-data lies if 0 is a legal stack value.

What to focus on

Guard with isEmpty. Underflow is a caller bug or a problem constraint you must state. Do not wrap around and pop a garbage slot.

Worked examples

empty

a = []
  1. size 0
  2. no top to remove

Result: underflow

after last pop

a = [7], pop then pop again
  1. first pop is legal
  2. second is empty

Result: second pop underflow

zero is data

a = [0], pop
  1. legal pop of 0
  2. not an empty result

Result: 0

Try it

Write pop(a). a is the stack, written [bottom, ..., top]. Empty means size 0. pop([]) must report an error, not return 0. Pop [7] once (legal) then again (illegal). Pop [0] returns 0. That is data, not underflow. [] is underflow. [7] then []: second pop is underflow. [0] pops 0.

The stack may be empty. Values are integers, including 0. Returning 0 is not a valid empty pop.