Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-in, first-out order.
Algorithm
Basic Implementation
basic.pl
use strict;
use warnings;
sub render { return join(" -> ", @_); }
my @stack;
push @stack, $_ for (10, 20, 30);
my @popped;
push @popped, pop @stack while @stack;
print render(@popped), "\n";
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
my @stackdeclares the stack as a Perl array with the@sigil.- The replay starts with an empty stack:
[]. - Push uses
push @stack, $_ for (10, 20, 30), appending each value to the end of the array. - After the pushes, the stack is
[10, 20, 30]; the top is the rightmost value,30. my @poppedrecords values returned by pop operations.- Pop uses
pop @stack, which removes and returns the last array element. push @popped, pop @stack while @stackrepeats while the stack is non-empty; in that condition,@stackis in scalar context and means length.- The first pop returns
30, leaving stack[10, 20]and popped[30]. - The remaining pops return
20and10, leaving stack[]and popped[30, 20, 10]. render(@popped)joins the popped values with" -> ".print render(@popped), "\n"outputs30 -> 20 -> 10.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.