Handle an empty stack
Updated
Empty is a real state: size 0, no top, pop and peek are illegal. Push onto empty is legal and produces a one-item stack.
What to focus on
Before peek or pop, ask: is the stack empty? If yes, take the empty path. Do not invent a top. isEmpty is the guard.
Worked examples
no peek
a = []- size 0
- do not read a top
Result: peek illegal
push onto empty
a = [], push 4- the new stack is [4]
- 4 is top and bottom
Result: [4]
pop empty
a = []- there is nothing to remove
Result: error / empty, not 0
Try it
Write isEmpty(a), peek(a), and pop(a). a is the stack, written [bottom, ..., top]. Empty means size 0 and there is no top. On [] isEmpty is true. peek and pop must report an error, not return 0. Push 4 onto [] and then peek is legal. []: isEmpty true. After push 4, peek is 4.
You will see [] and one push onto []. Values are integers, including 0. Returning 0 is not a valid empty peek or pop.