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 Scala 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.scala
def render(values: Seq[Int]): String = values.mkString(" -> ")
var queue = scala.collection.mutable.Queue[Int]()
for (value <- List(10, 20, 30)) queue.enqueue(value)
var removed = List[Int]()
while (queue.nonEmpty) removed = removed :+ queue.dequeue()
println(render(removed))
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
var queue = scala.collection.mutable.Queue[Int]()creates the mutable Scala queue used by the replay.- The enqueue loop
for (value <- List(10, 20, 30)) queue.enqueue(value)adds values at the back in input order. var removed = List[Int]()starts as an immutable Scala list value, but thevarbinding is reassigned after each dequeue.- The loop guard
while (queue.nonEmpty)prevents callingdequeue()on an empty queue, so this source has noOptionreturn or sentinel path. queue.dequeue()removes and returns the front value;removed = removed :+ queue.dequeue()appends that returned value to the end of the output list.- The trace shows
queuemoving from[]to[10, 20, 30], then the first dequeue producingremoved = [10]andqueue = [20, 30]. - The remaining dequeues leave
removed = [10, 20, 30]andqueue = []. render(values: Seq[Int])usesmkString(" -> "), soprintln(render(removed))writes10 -> 20 -> 30.