Transfer from one stack to another
Updated
Transfer pops from src and pushes onto dst until src is empty, or until a stop. Order reverses: dst's top is src's old bottom. Two transfers restore order. Queue-with-two-stacks uses that.
What to focus on
While src not empty: dst.push(src.pop()). Transferring from [] does nothing. Do not alias the stacks and pop/push the same one.
Worked examples
full reverse
src = [4, 1, 9], dst = []- pop 9 push dst, pop 1, pop 4
- dst [9, 1, 4] top 4
Result: src [], dst [9, 1, 4]
two transfers
src = [4, 1, 9], to dst then back to src- first reverse, second reverse
- src [4, 1, 9] again
Result: src [4, 1, 9]
empty src
src = [], dst = [7]- no moves
Result: src [], dst [7]
Try it
Write transfer(src, dst). src is the stack you pop. dst is the stack you push. Pop from src and push onto dst until src is empty. Print both stacks. A second transfer restores order. Transferring from [] is a no-op. src = [4, 1, 9], dst = [] → src [], dst [9, 1, 4]. src = [4, 1, 9], to dst then back to src → src [4, 1, 9]. src = [], dst = [7] → src [], dst [7].
src may be empty, which is a no-op. Values are integers. Transfer pops at most src.size times.