awelgorithms

Reject peek on empty

Updated

Peek on [] is the same class of error as pop on []: no top exists. Returning 0 is wrong. Returning a sentinel is only ok if the problem defines one.

What to focus on

Call isEmpty first, or let peek throw. After a drain loop, the next peek is illegal. One-item peek is legal.

Worked examples

empty

a = []
  1. no top

Result: illegal

after drain

a = [7], pop, then peek
  1. now empty

Result: illegal

zero is data

a = [0]
  1. peek 0

Result: legal — 0 is a value

Try it

Write peek(a). a is the stack, written [bottom, ..., top]. Empty means size 0 and there is no top. peek([]) reports an error, not 0. After popping [7], peek is illegal. peek([0]) is 0. [] is illegal. [7] then pop then peek is illegal. [0] peeks 0.

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