Stacks and Queues
Queue from Two Stacks
Implement queue behavior with an input stack and an output stack.
Algorithm
Basic Implementation
basic.pl
use strict;
use warnings;
sub render { return join(" -> ", @_); }
my @in_stack;
my @out_stack;
push @in_stack, $_ for (10, 20, 30);
push @out_stack, pop @in_stack while @in_stack;
my @removed;
push @removed, pop @out_stack while @out_stack;
print render(@removed), "\n";
Complexity
- Time: O(1) amortized per operation
- Space: O(n)
Implementation notes
my @in_stackandmy @out_stackare the two Perl arrays used as stacks; both use the@sigil.- The replay starts with both stacks empty: input
[], output[]. - Enqueue uses
push @in_stack, $_ for (10, 20, 30), appending each value to the top of the input stack. - After enqueue, the input stack is
[10, 20, 30]and the output stack is still[]. - Transfer uses
push @out_stack, pop @in_stack while @in_stack. - In that
while @in_stackcondition,@in_stackis in scalar context, so it means "while the stack has length". pop @in_stackremoves from the end:30, then20, then10.push @out_stack, ...appends those popped values, giving output stack[30, 20, 10]and emptying the input stack.- Dequeue then uses
push @removed, pop @out_stack while @out_stack. - Popping the output stack returns
10, then20, then30, which restores FIFO order. - The trace ends with removed values
[10, 20, 30]and output stack[]. render(@removed)joins the removed values with" -> ", andprint render(@removed), "\n"outputs10 -> 20 -> 30.
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.