awelgorithms

Keep a top index

Updated

topIndex is the index of the current top, or -1 when empty. Push writes at topIndex+1 then increments. Pop reads at topIndex then decrements.

What to focus on

Do not keep topIndex at next-free-slot and also at current-top without saying which. Pick one convention and stick to it. Here topIndex is the current top.

Worked examples

three

a = [4, 1, 9], topIndex = 2
  1. a[2] is 9

Result: topIndex 2

after pop

a = [4, 1, 9], topIndex = 2, pop
  1. topIndex 2 → 1
  2. a[1] is 1

Result: topIndex 1

empty

a = [], topIndex = -1
  1. no legal a[topIndex]

Result: topIndex -1

Try it

Write topIndexOf(a, topIndex). a is the stack in an array. topIndex is the index of the current top, or -1 when empty. Peek is a[topIndex] only when topIndex >= 0. On [4, 1, 9] topIndex 2, after pop topIndex 1, after pop pop topIndex -1.

Values are integers. Empty uses topIndex = -1. You may pop down to empty.