awelgorithms

Prove a stack copy does not share storage

Updated

After copy, push or pop on b must leave a identical. Shared backing means b.pop() mutates a. Check identity of the array or head node, not only equal values.

What to focus on

b = a is alias, not copy. b = a.slice() of the occupied prefix is a copy for arrays. For objects on the stack, a shallow copy still shares those objects. Say so if values are mutable.

Worked examples

independent

a = [4, 1, 9], b = copy(a), pop b
  1. a still size 3

Result: no share

alias

a = [4, 1, 9], b = a, pop b
  1. a size 2

Result: shared — fail

empty

a = [], b = copy(a), push b 4
  1. a still []

Result: no share

Try it

Write copyIndependent(a). a is the stack. Copy a into b, then mutate b. Return whether a is unchanged. Alias b=a must fail. a = [4, 1, 9], b = copy(a), pop b → no share. a = [4, 1, 9], b = a, pop b → shared — fail. a = [], b = copy(a), push b 4 → no share.

Values are integers. You may copy an empty stack and push onto the copy.