Store a stack in an array
Updated
An array-backed stack uses consecutive slots. Index 0 is the bottom. The last occupied index is the top. Unused slots past the top are not on the stack.
What to focus on
The stack is not the whole array length. Logical size and allocated capacity can differ. Walking past size reads garbage, not stack items.
Worked examples
tight
a = [4, 1, 9]- capacity 3, size 3
- top at index 2
Result: slots 0..2 are the stack
spare capacity
a = [4, 1, 9, _, _], size 3- indices 3,4 are unused
Result: stack is still [4, 1, 9]
empty
a = [_, _, _], size 0- no occupied slot
Result: []
Try it
Write arrayStack(a). a is the occupied prefix of the backing array. size is how many slots are on the stack. capacity is the allocated length. Mark size versus capacity. Slot 4 is not peek when size is 3. Size 0 with leftover slots is still empty. Capacity 5 holding [4, 1, 9]: size 3, top at index 2, slots 3 and 4 unused.
Capacity is at least size. Values are integers. size 0 is allowed.