awelgorithms

Check whether a stack is empty

Updated

isEmpty is size == 0, or top-index < 0, or head == null. It is the guard for peek and pop. A nonempty stack with top 0 is not empty.

What to focus on

Do not use peek==null as emptiness if null is a stored value. Size (or an explicit flag) is the contract. Empty after the last pop becomes true.

Worked examples

empty

a = []
  1. size 0

Result: true

nonempty

a = [4, 1, 9]
  1. size 3

Result: false

zero on top

a = [0]
  1. size 1
  2. 0 is a value

Result: false

Try it

Write isEmpty(a). a is the stack, written [bottom, ..., top]. Empty means size 0. A stack whose top is 0 is not empty. Return true only when size is 0. After popping the last item it becomes true. isEmpty([]) is true. isEmpty([4, 1, 9]) is false. isEmpty([0]) is false.

Values are integers, including 0 on a one-item stack. The stack may be empty.