awelgorithms

Pop from a one-item stack

Updated

A one-item stack's top is also its bottom. Popping it leaves empty. That is the same pop code: size goes from 1 to 0, and there is no new top.

What to focus on

Do not leave a ghost value in the backing slot as the top. Size 0 means empty even if the array still holds a stale 7.

Worked examples

only 7

a = [7], pop
  1. yield 7
  2. size 0

Result: []

not the three-item case

a = [4, 1, 9], pop
  1. leaves [4, 1]
  2. not empty

Result: [4, 1]

zero is a value

a = [0], pop
  1. yield 0
  2. size 0

Result: []

Try it

Write pop(a). a is the stack, written [bottom, ..., top]. Size, not a leftover slot, decides emptiness. Pop a one-item stack to []. Popping one item from a three-item stack does not empty it. Popping 0 returns 0. Pop [7] → []. Pop [4, 1, 9] once → [4, 1]. Pop [0] returns 0 and leaves [].

The stack is non-empty before the pop. Values are integers, including 0.