awelgorithms

Handle stack overflow

Updated

A bounded stack rejects push when size == capacity instead of growing. Overflow is an error, not a wrap to index 0 (that is a different structure).

What to focus on

isFull is size == capacity. Empty is not full unless capacity is 0. Tell the caller. Do not overwrite the bottom.

Worked examples

full reject

a = [4, 1, 9], cap 3, push 8
  1. size==cap
  2. do not write

Result: overflow, stack unchanged

room

a = [4, 1], cap 3, push 9
  1. size 2 < 3

Result: [4, 1, 9]

empty cap 3

a = [], cap 3, push 4
  1. not full

Result: [4]

Try it

Write boundedPush(a, x). a is the array-backed stack. x is the integer to push. capacity is a fixed limit. If size equals capacity, reject the push and leave the stack unchanged. Do not wrap and overwrite the bottom. With cap 3, push 8 onto [4, 1, 9] refuses. Push 9 onto [4, 1] succeeds.

Capacity is a positive integer. Values are integers. You may push onto empty. Full is in scope. That is this skill.