awelgorithms

Push one value

Updated

Push adds a value as the new top. Everything already on the stack stays, now one slot deeper. Size increases by 1.

What to focus on

After push(x), peek is x. The old top is still there, buried. Empty push makes a one-item stack. You do not shift buried values by hand. The structure does that.

Worked examples

onto three

a = [4, 1, 9], push 8
  1. 8 becomes top
  2. 9 is now under 8

Result: [4, 1, 9, 8] · top 8

onto one

a = [7], push 3
  1. 3 on top of 7

Result: [7, 3] · top 3

onto empty

a = [], push 4
  1. 4 is top and bottom

Result: [4]

Try it

Write push(a, x). a is the stack, written [bottom, ..., top]. x is the integer to add as the new top. Add x on top. Size increases by 1. Peek must be x. Push 8 onto [4, 1, 9] → [4, 1, 9, 8]. Push 3 onto [7] → [7, 3]. Push 4 onto [] → [4].

Values are integers. You may push onto an empty stack.