awelgorithms

Pop several values in order

Updated

Repeated pops yield the reverse of the push order. From [4, 1, 9] three pops are 9, then 1, then 4. After that the stack is empty.

What to focus on

You cannot pop 4 first. Each pop peels one layer. A loop that pops until empty is how you drain a stack.

Worked examples

drain

a = [4, 1, 9], pop pop pop
  1. 9 then 1 then 4

Result: yields 9, 1, 4 · []

partial

a = [4, 1, 9], pop pop
  1. 9 then 1
  2. 4 remains

Result: [4]

one left

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

Result: [4]

Try it

Write drain(a). a is the stack, written [bottom, ..., top]. Pop until empty and print each popped value. The sequence must be reverse of push order. Drain [4, 1, 9] prints 9, 1, 4. Pop twice from [4, 1, 9] leaves [4]. Pop once from [4, 1] leaves [4].

The stack starts non-empty. You pop at most size times. Values are integers.