awelgorithms

Copy a stack

Updated

Copying makes a second stack with the same bottom-to-top order. Mutating the copy must not change the original. A single pour into a helper reverses. Pour twice, or copy the backing array 0..size-1, to keep order.

What to focus on

Array-backed: copy the occupied prefix. List-backed: copy the chain. Empty copy is empty. Aliasing the same backing array is not a copy.

Worked examples

three

a = [4, 1, 9]
  1. b gets [4, 1, 9]
  2. top 9 both

Result: b = [4, 1, 9]

then pop copy

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

Result: a unchanged

empty

a = []
  1. b []

Result: []

Try it

Write copy(a). a is the stack written bottom to top. Return a new stack with the same order. Pop on the copy must not change a. You may copy []. a = [4, 1, 9] → b = [4, 1, 9]. a = [4, 1, 9], b = copy, pop b → a unchanged. a = [] → [].

Values are integers. You may copy an empty stack.