Part 17 / Topic 4 of 12
ArrayDeque as a stack and as a queue
kotlin.collections.ArrayDeque ("deck," double-ended queue) gives you both a stack (LIFO: last in, first out — addLast/removeLast/last() at one end) and a queue (FIFO: first in, first out — addLast/removeFirst/first()) from the same class. This one is genuinely Kotlin's own, not borrowed from java.util the way PriorityQueue is (section 10) — it shipped in the Kotlin standard library itself from Kotlin 1.4 onward, specifically so Kotlin code never needs java.util.Stack (legacy, synchronized, slower) or a Queue-cast LinkedList.
Think of a stack of plates (you only ever take the top one) versus a queue at a ticket counter (first person in line is served first) — same deque class, two different ends used.
val callStack = ArrayDeque<String>()
callStack.addLast("main()")
callStack.addLast("placeOrder()")
callStack.addLast("validatePincode()")
// ... callStack.removeLast() removes "validatePincode()" first: LIFO
val printQueue = ArrayDeque<String>()
printQueue.addLast("invoice-101.pdf")
printQueue.addLast("invoice-102.pdf")
// ... printQueue.removeFirst() removes "invoice-101.pdf" first: FIFO
$ kotlinc DequeDemo.kt -include-runtime -d deque.jar
$ java -jar deque.jar
-- ArrayDeque as a stack (LIFO) --
stack, top to bottom: [validatePincode(), placeOrder(), main()]
peek (top, not removed): validatePincode()
pop: validatePincode()
after pop: [placeOrder(), main()]
-- ArrayDeque as a queue (FIFO) --
queue, head to tail: [invoice-101.pdf, invoice-102.pdf, invoice-103.pdf]
peek (head, not removed): invoice-101.pdf
poll: invoice-101.pdf
after poll: [invoice-102.pdf, invoice-103.pdf]
-- balanced brackets, using a stack --
{"city":["Pune","Delhi"]} -> true
{"city":["Pune"} -> false
-- sliding window maximum, using ArrayDeque at both ends --
weights: [4, 8, 2, 9, 5, 7, 1]
max of every window of 3: [8, 9, 9, 9, 7]
Balanced brackets is the canonical stack problem: push every opening bracket, and on every closing bracket, pop and check it matches — an unmatched or leftover bracket means the stack is non-empty or popped from empty at the wrong time. The when block in isBalanced makes the "three opening characters, three closing characters, everything else ignored" shape read almost like the rule itself. The sliding-window maximum at the end uses both ends of the same deque at once: old, now-out-of-window indices drop off the front, and indices whose value can never be the window's max again (because a bigger value just arrived) drop off the back — the front of the deque is always the current window's maximum.
Full program: examples/stacks-queues/DequeDemo.kt.
Real-world build 1: an undo button
Every text editor's undo button is two stacks: an undo stack of actions already applied, and a redo stack of actions just undone. Undo pops the most recent action, reverses it on the document, and pushes the original action onto the redo stack (not its reverse — redo needs to replay the original, not reverse the reversal). Typing anything new clears the redo stack, because the old "future" no longer exists once you've branched off into a new one.
Action here is a deliberately plain class, not a data class — it carries behaviour (apply/inverse), not just data to compare or copy, which is exactly the line Stage 2's tour of class-declaration keywords draws between the two.
fun undo(): Boolean {
if (undoStack.isEmpty()) return false
val last = undoStack.removeLast()
last.inverse(document) // cancel the action out on the document
redoStack.addLast(last) // remember the ORIGINAL action, to redo it later
return true
}
fun redo(): Boolean {
if (redoStack.isEmpty()) return false
val last = redoStack.removeLast()
last.apply(document) // re-apply the original action, exactly as it ran the first time
undoStack.addLast(last)
return true
}
$ kotlinc UndoButtonDemo.kt -include-runtime -d undo.jar
$ java -jar undo.jar
after type "Buy milk": "Buy milk"
after type ", eggs": "Buy milk, eggs"
after type ", bread": "Buy milk, eggs, bread"
after 1 undo: "Buy milk, eggs"
after 2 undos: "Buy milk"
after 1 redo: "Buy milk, eggs"
after typing "!" (new action): "Buy milk, eggs!"
redo after a new action: false (the ", bread" redo was discarded)
after undoing everything: ""
Notice typing "!" after undoing twice does not bring back ", bread" on a later redo — redoStack.clear() runs the moment any fresh action is typed, which is exactly the behaviour every editor's undo button has trained you to expect, now visible as two ArrayDeques.
Full program: examples/stacks-queues/UndoButtonDemo.kt.
Done here? The practice set for Part 17 — including the solutions — is on the part page.