awelgorithms

Return the popped value

Updated

Pop has two results: the value that left, and the stack that remains. Forgetting to return the value is a void-pop. Forgetting to update the stack leaks the old top as still there.

What to focus on

Use the returned value if the problem needs it (matching brackets, expressions). If you only need to discard, you still must update size/top.

Worked examples

use value

a = [4, 1, 9], x = pop()
  1. x is 9
  2. stack [4, 1]

Result: x=9

discard

a = [4, 1, 9], pop and ignore x
  1. stack still must become [4, 1]

Result: [4, 1]

zero is a value

a = [4, 0], x = pop()
  1. x is 0
  2. stack [4]

Result: x=0, not 'empty'

Try it

Write pop(a). a is the stack, written [bottom, ..., top]. Return the popped value and update the stack. 0 is a real value, not empty. Capture 9 from [4, 1, 9]. Pop-and-discard still leaves [4, 1]. Pop 0 from [4, 0] and return 0.

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