awelgorithms

Pop the top

Updated

Pop removes the top and returns it. The new top is whatever was underneath. Size decreases by 1.

What to focus on

After pop on [4, 1, 9] you get 9 and the stack is [4, 1]. You do not return 4. Buried values do not move except that they sit one closer to the top.

Worked examples

three items

a = [4, 1, 9], pop
  1. yield 9
  2. leave [4, 1]

Result: popped 9, stack [4, 1]

two items

a = [4, 1], pop
  1. yield 1
  2. leave [4]

Result: popped 1, stack [4]

one item

a = [7], pop
  1. yield 7
  2. leave []

Result: popped 7, stack []

Try it

Write pop(a). a is the stack, written [bottom, ..., top]. Remove and return the top. The new top is the value that was underneath. On [4, 1, 9] the first pop is 9, not 4. Then [4, 1] pops 1. [7] pops 7 and leaves [].

The stack is non-empty before each pop. Values are integers.