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]- b gets [4, 1, 9]
- top 9 both
Result: b = [4, 1, 9]
then pop copy
a = [4, 1, 9], b = copy, pop b- b [4, 1]
- a still [4, 1, 9]
Result: a unchanged
empty
a = []- 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.