Peek the top
Updated
Peek (or top) returns the top value without removing it. Size stays the same. After peek, a pop still yields that same value.
What to focus on
peek is not pop. Calling peek twice in a row returns the same value. You use it to decide whether to pop without committing.
Worked examples
three
a = [4, 1, 9]- see 9
- stack unchanged
Result: peek 9, still [4, 1, 9]
one
a = [7]- see 7
Result: peek 7, still [7]
then pop
a = [4, 1, 9], peek then pop- peek 9
- pop 9
- now [4, 1]
Result: peek then pop both see 9
Try it
Write peek(a). a is the stack, written [bottom, ..., top]. Return the top without removing it. Size stays the same. Peek twice, then pop, and peek changes. On [4, 1, 9] peek is 9 and size stays 3. After pop, peek is 1.
The stack is non-empty. Values are integers.