Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-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.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.
Visual walkthrough
Basic Implementation
basic.pl
use strict;
use warnings;
sub render { return join(" -> ", @_); }
my @queue;
push @queue, $_ for (10, 20, 30);
my @removed;
push @removed, shift @queue while @queue;
print render(@removed), "\n";
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
my @queuedeclares the queue as a Perl array with the@sigil.- The queue starts empty; the trace begins with
[]. - Enqueue uses
push @queue, $_ for (10, 20, 30), appending each value to the back of the array. - After the enqueue step, the replayed queue is
[10, 20, 30]. my @removedstores the values as they are dequeued.- Dequeue uses
shift @queue, which removes and returns the front element of the Perl array. push @removed, shift @queue while @queuerepeats while the queue array is non-empty; in that condition,@queueis in scalar context and means length.- The first dequeue returns
10, leaving queue[20, 30]and removed[10]. - The remaining dequeues return
20and30, leaving queue[]and removed[10, 20, 30]. render(@removed)receives the removed values as a list and joins them with" -> ".print render(@removed), "\n"outputs10 -> 20 -> 30.