awelgorithms

Push by writing then incrementing

Updated

With topIndex as current top, push does: topIndex += 1; a[topIndex] = x. Empty starts at -1, so the first push writes index 0. Check capacity first.

What to focus on

If you increment after the write, you are using the other convention (topIndex = next free). Mixing them overwrites the old top or skips a slot.

Worked examples

onto three

a = [4, 1, 9], topIndex = 2, push 8
  1. topIndex ← 3
  2. a[3] ← 8

Result: [4, 1, 9, 8]

onto empty

a = [], topIndex = -1, push 4
  1. topIndex ← 0
  2. a[0] ← 4

Result: [4]

wrong order

a = [4, 1, 9], topIndex = 2, write a[2] ← 8 then increment
  1. overwrites 9

Result: lost 9 — bug

Try it

Write pushAt(a, x, topIndex). a is the array-backed stack. x is the integer to push. topIndex is the current top, or -1 when empty. Increment topIndex, then write x. Writing at the old topIndex overwrites the old top. a = [4, 1, 9], topIndex = 2, push 8 → [4, 1, 9, 8]. a = [], topIndex = -1, push 4 → [4]. Writing at the old topIndex loses 9.

Capacity is enough for the push. Values are integers. You may push onto empty (topIndex starts at -1).