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.kt
import java.util.ArrayDeque
fun render(values: List<Int>) = values.joinToString(" -> ")
fun main() {
val stack = ArrayDeque<Int>()
for (value in listOf(10, 20, 30)) stack.addLast(value)
val popped = mutableListOf<Int>()
while (!stack.isEmpty()) popped.add(stack.removeLast())
println(render(popped))
}
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- Kotlin imports
java.util.ArrayDequeand createsval stack = ArrayDeque<Int>(); the binding is not rebound, but the deque contents mutate. - Push uses
stack.addLast(value)forlistOf(10, 20, 30), making the back of the deque the stack top. - Pop uses
stack.removeLast()insidewhile (!stack.isEmpty()), so the newest value is removed first. - The emptiness guard avoids the exception path for
removeLast()on an empty deque; values are non-nullInts, not nullable pop results. - Popped values are collected in
val popped = mutableListOf<Int>(), a separate mutable output list. - The trace shows
stack=[], then[10, 20, 30], then popping30leaves[10, 20], and the final popped order is[30, 20, 10]with an empty stack. render(values: List<Int>)usesjoinToString(" -> "), andprintln(render(popped))prints30 -> 20 -> 10.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.