Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-in, first-out order.
Algorithm
The replay uses the same three values in every language, so this Perl DSA implementation can be compared directly with the rest of the DSA track.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.
Visual walkthrough
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.