awelgorithms

Use two stacks together

Updated

Two stacks are two independent LIFOs. They share nothing unless you transfer. Names like inStack and outStack, or left and right, keep the roles clear. Peeking one does not peek the other.

What to focus on

Draw both after every op. A bug that pops the wrong stack looks like a random reorder. Tests should say which stack changed.

Worked examples

independent

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

Result: a [4], b [9]

both empty

a = [], b = []
  1. neither has a top

Result: both empty

fill one

a = [], b = [9, 8], push a 4
  1. a [4]
  2. b unchanged

Result: a [4], b [9, 8]

Try it

Write twoStacks(a, b). a is the first stack, bottom to top. b is the second stack, bottom to top. Pop and push only the stack the step names. Print both stacks after each op. Empty/empty needs two isEmpty checks. a = [4, 1], b = [9] → a [4], b [9]. a = [], b = [] → both empty. a = [], b = [9, 8], push a 4 → a [4], b [9, 8].

Values are integers. Either stack may be empty. Pop only a non-empty stack.