Stacks and Queues
Queue from Two Stacks
Implement queue behavior with an input stack and an output stack.
Algorithm
The replay uses the same three values in every language, so this Ruby DSA implementation can be compared directly with the rest of the DSA track.
input stack
Enqueue pushes new values onto the input stack.
output stack
When the output stack is empty, transferring all input values reverses them into dequeue order.
Visual walkthrough
Basic Implementation
basic.rb
in_stack = []
out_stack = []
[10, 20, 30].each { |value| in_stack.push(value) }
out_stack.push(in_stack.pop) until in_stack.empty?
removed = []
removed << out_stack.pop until out_stack.empty?
puts removed.join(" -> ")
Complexity
- Time: O(1) amortized per operation
- Space: O(n)
Implementation notes
- This checked Ruby source is straight-line code, not a queue class:
in_stackandout_stackare both arrays used as stacks. - Enqueue uses
in_stack.push(value)for10,20, and30, leaving the input stack as[10, 20, 30]. - Transfer uses
out_stack.push(in_stack.pop) until in_stack.empty?; eachpopremoves and returns the last input value. - That transfer reverses the stack order, producing
out_stackas[30, 20, 10]in the trace. - Dequeue order then comes from
out_stack.pop, which removes10, then20, then30. - Both transfer and removal loops are guarded with
empty?, so this lesson does not rely on RubyArray#popreturningnilfrom an empty array. removed << out_stack.poprecords the returned values as[10, 20, 30].puts removed.join(" -> ")prints10 -> 20 -> 30.