awelgorithms

Push onto an empty stack

Updated

Pushing onto empty is how a stack gets its first item. After that push, size is 1, peek is that value, and pop would return it and leave empty again.

What to focus on

There is no insert-at-bottom special case. Empty's only legal mutation is push (or leaving it empty). The new item is both top and bottom.

Worked examples

first item

a = [], push 4
  1. size 0 → 1
  2. top 4

Result: [4]

then it is nonempty

a = [4], push 1
  1. ordinary nonempty push

Result: [4, 1]

zero is a value

a = [], push 0
  1. 0 is data, not empty

Result: [0] · top 0

Try it

Write push(a, x). a is the stack, written [bottom, ..., top]. x is the integer to add. Empty starts as []. Push onto empty, then push again. 0 is a real value, not empty. [] push 4 → [4]. Then push 1 → [4, 1]. [] push 0 → [0], peek is 0.

The stack starts empty, or has just received its first push. Values are integers, including 0.