awelgorithms

Keep the new top after push

Updated

The caller who holds a top pointer or a returned stack must use the stack after the push. A snapshot of the old top is stale.

What to focus on

If the stack is a shared object, push mutates it in place and peek changes. If push returns a new stack (immutable), you must keep the return value.

Worked examples

in place

a = [4, 1, 9], push 8, then peek
  1. peek is 8
  2. not 9

Result: top 8

stale peek

a = [4, 1, 9], saved = old top 9, then push 8
  1. saved is not the top anymore

Result: saved 9 is buried

empty then peek

a = [], push 4, peek
  1. must peek after the push

Result: top 4

Try it

Write push(a, x). a is the stack, written [bottom, ..., top]. x is the integer to add as the new top. Peek immediately after the push. A cached old top is buried, not current. Push 8 onto [4, 1, 9] and peek is 8, not 9. Push 4 onto [] and peek is 4.

Values are integers. You may push onto empty. After each push The stack may be empty.