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 Scala 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.scala
def render(values: Seq[Int]): String = values.mkString(" -> ")
var stack = List[Int]()
for (value <- List(10, 20, 30)) stack = value :: stack
var popped = List[Int]()
while (stack.nonEmpty) { popped = popped :+ stack.head; stack = stack.tail }
println(render(popped))
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
var stack = List[Int]()uses a ScalaList[Int]as the stack storage; thevarbinding is reassigned as values are pushed and popped.- Push is
stack = value :: stack, so each new value is added to the front, which acts as the raw ScalaListhead and stack top. var popped = List[Int]()records the pop order separately from the remaining stack.- The loop guard
while (stack.nonEmpty)prevents readingheadortailon an empty list, so this source has noOptionreturn or sentinel path. - Pop reads the top with
stack.head, appends it topoppedwith:+, then drops it withstack = stack.tail. - After the pushes, the raw Scala list head order is
List(30, 20, 10). The trace displays the stack as[10, 20, 30], a bottom-to-top visual order. - The first pop reads raw
stack.headas30, recordspopped = [30], and the trace shows the remaining stack view as[10, 20]. - The remaining pops leave
popped = [30, 20, 10]andstack = []. render(values: Seq[Int])usesmkString(" -> "), soprintln(render(popped))writes30 -> 20 -> 10.