Queues, stacks, and deques
suggest changeA stack is last-in, first-out (LIFO): you push items on top and pop them from the top. A queue is first-in, first-out (FIFO): you add items at the back and take them from the front. A deque (double-ended queue, pronounced "deck") lets you add and remove at both ends, so it can act as either.
Dart has no Stack class. A plain List is already a good stack. For queues and deques, dart:collection provides the Queue interface with two implementations, ListQueue and DoubleLinkedQueue. For priority queues there is PriorityQueue in package:collection.
This article covers:
- using a
Listas a stack, and wrapping it in aStackclass - why a
Listis a bad queue QueueandListQueueas a queue and as a deque- breadth-first and depth-first traversal
- a sliding-window maximum with a deque
- a bounded history that keeps the last N items
DoubleLinkedQueueand its entries- modifying a queue while iterating
PriorityQueuefrompackage:collection- an async queue that consumers can wait on
The examples were run with Dart 3.13.
A List as a stack
add pushes onto the end of the list, removeLast pops from the end and last peeks at the top. All three are O(1) (add is amortized O(1), since the list occasionally grows its backing storage):
void main() {
final stack = <String>[];
stack.add('a'); // push
stack.add('b');
stack.add('c');
print(stack);
print(stack.last); // peek
print(stack.removeLast()); // pop
print(stack.removeLast());
print(stack);
print(stack.isEmpty);
stack.removeLast();
try {
stack.removeLast();
} on RangeError catch (e) {
print('pop on empty stack: $e');
}
print(stack.lastOrNull);
}
Output:
[a, b, c]
c
c
b
[a]
false
pop on empty stack: RangeError (length): Invalid value: Valid value range is empty: -1
null
Popping an empty list throws a RangeError, and last on an empty list throws a StateError. If an empty stack is a normal situation, check isEmpty first or use lastOrNull, which returns null instead of throwing.
Always use the end of the list as the top of the stack. insert(0, x) and removeAt(0) shift every other element and are O(n).
A classic stack problem is checking that brackets are balanced. Every opening bracket is pushed. A closing bracket must match the most recently opened one:
bool isBalanced(String text) {
const pairs = {')': '(', ']': '[', '}': '{'};
final stack = <String>[];
for (final ch in text.split('')) {
if (pairs.containsValue(ch)) {
stack.add(ch);
} else if (pairs.containsKey(ch)) {
if (stack.isEmpty || stack.removeLast() != pairs[ch]) return false;
}
}
return stack.isEmpty;
}
void main() {
for (final s in ['(a[b]{c})', '([)]', '((', 'f(x) = {y: [1, 2]}']) {
print('${s.padRight(20)} ${isBalanced(s)}');
}
}
Output:
(a[b]{c}) true
([)] false
(( false
f(x) = {y: [1, 2]} true
A Stack class
A bare List lets any code call insert(0, ...) or index into the middle. If you want the type to say "this is a stack", wrap the list in a small generic class that only exposes stack operations:
class Stack<T> {
final List<T> _items = [];
void push(T value) => _items.add(value);
T pop() {
if (_items.isEmpty) throw StateError('pop from empty stack');
return _items.removeLast();
}
T? peek() => _items.lastOrNull;
bool get isEmpty => _items.isEmpty;
int get length => _items.length;
/// Elements from top to bottom.
Iterable<T> get topDown => _items.reversed;
@override
String toString() => 'Stack(top -> ${topDown.join(', ')})';
}
void main() {
final history = Stack<String>()
..push('/home')
..push('/products')
..push('/products/42');
print(history);
print('back to: ${(history..pop()).peek()}');
print(history.length);
history
..pop()
..pop();
try {
history.pop();
} on StateError catch (e) {
print(e.message);
}
}
Output:
Stack(top -> /products/42, /products, /home)
back to: /products
2
pop from empty stack
peek returns T?, which is ambiguous when T itself is nullable (Stack<int?>). If you store nulls, check isEmpty instead of relying on peek() == null.
Why a List is a bad queue
You can use a List as a queue with add and removeAt(0), and for a handful of items it works. But removeAt(0) moves every remaining element one slot to the left, so draining a list of n items costs O(n²). A ListQueue is a circular buffer: removing from the front only moves a start index, so it's O(1):
import 'dart:collection';
void main() {
const n = 50000;
final sw = Stopwatch()..start();
final list = List<int>.generate(n, (i) => i);
var sum = 0;
while (list.isNotEmpty) {
sum += list.removeAt(0); // shifts every remaining element
}
print('List.removeAt(0): ${sw.elapsedMilliseconds} ms (sum $sum)');
sw.reset();
final queue = ListQueue<int>.of(List.generate(n, (i) => i));
sum = 0;
while (queue.isNotEmpty) {
sum += queue.removeFirst(); // O(1)
}
print('Queue.removeFirst(): ${sw.elapsedMilliseconds} ms (sum $sum)');
}
Output with dart run (your timings will differ):
List.removeAt(0): 4245 ms (sum 1249975000)
Queue.removeFirst(): 7 ms (sum 1249975000)
Compiled with dart compile exe the list version took 763 ms and the queue version 1 ms. Doubling n roughly quadruples the list time. See Performance for more on measuring Dart code.
Queue as a FIFO queue
Queue lives in dart:collection. The Queue() constructor creates a ListQueue, which is the right choice almost always:
import 'dart:collection';
void main() {
final queue = Queue<int>(); // a ListQueue<int>
print(queue.runtimeType);
queue.add(1); // same as addLast
queue.addLast(2);
queue.addAll([3, 4]);
print(queue);
print(queue.first); // peek at the front
print(queue.removeFirst()); // dequeue
print(queue.removeFirst());
print(queue);
print(queue.length);
queue.clear();
try {
queue.removeFirst();
} on StateError catch (e) {
print('dequeue on empty queue: ${e.message}');
}
print(queue.firstOrNull);
}
Output:
ListQueue<int>
{1, 2, 3, 4}
1
1
2
{3, 4}
2
dequeue on empty queue: No element
null
Note that a queue prints with curly braces, like a set, even though it keeps duplicates and insertion order. Removing from an empty queue throws StateError, unlike the RangeError you get from an empty list.
Queue as a deque
The same Queue supports both ends: addFirst, addLast, removeFirst and removeLast are all O(1) for ListQueue. Because Queue is an Iterable, you also get contains, map, where, elementAt and the rest:
import 'dart:collection';
void main() {
final deque = Queue<String>.of(['b', 'c']);
deque.addFirst('a');
deque.addLast('d');
print(deque);
print(deque.removeFirst());
print(deque.removeLast());
print(deque);
print('${deque.first} ... ${deque.last}');
print(deque.contains('c'));
print(deque.elementAt(1));
print(deque.map((s) => s.toUpperCase()).toList());
deque.addAll(['x', 'yy', 'zzz']);
deque.removeWhere((s) => s.length > 1);
print(deque);
}
Output:
{a, b, c, d}
a
d
{b, c}
b ... c
true
c
[B, C]
{b, c, x}
Queue is not a List. It has no [] operator, no insert in the middle and no reversed getter. elementAt is O(1) on a ListQueue, but if you need a lot of index-based access, convert with toList() or reconsider the data structure:
import 'dart:collection';
void main() {
final q = ListQueue<int>(1000); // initial capacity hint
q.addAll([10, 20, 30]);
// q[0]; // compile error: Queue has no [] operator
print(q.elementAt(2));
print(q.toList()[0]);
print(q.take(2));
print(q.toList().reversed); // Queue has no reversed getter
}
Output:
30
10
(10, 20)
(30, 20, 10)
The ListQueue(1000) argument is an initial capacity, not a length. The queue starts empty but won't need to grow until it holds more than 1000 items.
Breadth-first and depth-first traversal
Queues and stacks are the core of graph and tree traversal. Breadth-first search (BFS) takes the oldest discovered node from a queue, so it visits nodes in order of distance from the start. That makes it find shortest paths in unweighted graphs:
import 'dart:collection';
/// Returns the shortest path from [start] to [goal], or null.
List<String>? shortestPath(
Map<String, List<String>> graph, String start, String goal) {
final cameFrom = <String, String?>{start: null};
final queue = Queue<String>()..add(start);
while (queue.isNotEmpty) {
final node = queue.removeFirst();
if (node == goal) {
final path = <String>[];
for (String? n = goal; n != null; n = cameFrom[n]) {
path.add(n);
}
return path.reversed.toList();
}
for (final next in graph[node] ?? const <String>[]) {
if (!cameFrom.containsKey(next)) {
cameFrom[next] = node;
queue.add(next);
}
}
}
return null;
}
void main() {
final graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': <String>[],
'G': ['A'],
};
print(shortestPath(graph, 'A', 'F'));
print(shortestPath(graph, 'A', 'G'));
}
Output:
[A, B, D, F]
null
Replace the queue with a stack and you get depth-first search. An explicit stack also replaces recursion when a tree is deep enough to overflow the call stack. Here both traversals are written as sync* generators:
import 'dart:collection';
class Node {
final String name;
final List<Node> children;
Node(this.name, [this.children = const []]);
}
Iterable<String> depthFirst(Node root) sync* {
final stack = <Node>[root];
while (stack.isNotEmpty) {
final node = stack.removeLast();
yield node.name;
stack.addAll(node.children.reversed); // leftmost child on top
}
}
Iterable<String> breadthFirst(Node root) sync* {
final queue = Queue<Node>()..add(root);
while (queue.isNotEmpty) {
final node = queue.removeFirst();
yield node.name;
queue.addAll(node.children);
}
}
void main() {
final tree = Node('root', [
Node('a', [Node('a1'), Node('a2')]),
Node('b', [Node('b1')]),
]);
print('DFS: ${depthFirst(tree).join(' ')}');
print('BFS: ${breadthFirst(tree).join(' ')}');
}
Output:
DFS: root a a1 a2 b b1
BFS: root a b a1 a2 b1
The two functions are identical except for the container and which end they take from.
Sliding-window maximum with a deque
Some algorithms need both ends at once. To find the maximum of every window of k consecutive values, keep a deque of indexes whose values decrease from front to back. The front is always the current maximum. Indexes that fall out of the window leave from the front, and values that can never be a maximum again leave from the back:
import 'dart:collection';
/// Maximum of every window of [k] consecutive values, in O(n).
List<int> slidingMax(List<int> values, int k) {
final window = Queue<int>(); // indexes; their values are decreasing
final result = <int>[];
for (var i = 0; i < values.length; i++) {
// Drop the index that slid out of the window.
if (window.isNotEmpty && window.first <= i - k) window.removeFirst();
// Smaller values at the back can never be a maximum again.
while (window.isNotEmpty && values[window.last] <= values[i]) {
window.removeLast();
}
window.addLast(i);
if (i >= k - 1) result.add(values[window.first]);
}
return result;
}
void main() {
print(slidingMax([1, 3, -1, -3, 5, 3, 6, 7], 3));
}
Output:
[3, 3, 5, 5, 6, 7]
Each index is added once and removed at most once, so the whole thing is O(n) instead of the O(n·k) of computing each window's maximum from scratch.
A bounded history
A deque is also the natural way to keep only the most recent N items: add at the back and drop from the front when full. Extending IterableBase gives the class length, contains, toList and every other Iterable method for free:
import 'dart:collection';
/// Keeps only the most recent [capacity] items.
class History<T> extends IterableBase<T> {
final int capacity;
final _items = ListQueue<T>();
History(this.capacity);
void add(T item) {
if (_items.length == capacity) _items.removeFirst();
_items.addLast(item);
}
@override
Iterator<T> get iterator => _items.iterator;
}
void main() {
final recent = History<String>(3);
for (final cmd in ['ls', 'cd src', 'git status', 'dart test', 'git diff']) {
recent.add(cmd);
print(recent.toList());
}
print(recent.length);
print(recent.contains('ls'));
}
Output:
[ls]
[ls, cd src]
[ls, cd src, git status]
[cd src, git status, dart test]
[git status, dart test, git diff]
3
false
The same pattern works for rate limiters (timestamps of the last N requests), undo buffers and log tails.
DoubleLinkedQueue and entries
DoubleLinkedQueue is a doubly linked list. For plain queue operations it's slower than ListQueue and uses more memory, because every element gets its own node object. Its one advantage is entries: handles to individual nodes that let you insert or remove next to a node in O(1), while you walk the list:
import 'dart:collection';
void main() {
final tasks = DoubleLinkedQueue<String>.of(['parse', 'check', 'emit']);
// Walk the nodes and insert next to one of them in O(1).
var entry = tasks.firstEntry();
while (entry != null) {
if (entry.element == 'check') {
entry.prepend('resolve'); // insert before
entry.append('optimize'); // insert after
}
entry = entry.nextEntry();
}
print(tasks);
// Remove a node while walking, without touching the others.
tasks.forEachEntry((e) {
if (e.element.startsWith('o')) e.remove();
});
print(tasks);
final last = tasks.lastEntry()!;
print('${last.previousEntry()?.element} -> ${last.element}');
}
Output:
{parse, resolve, check, optimize, emit}
{parse, resolve, check, emit}
check -> emit
With forEachEntry you can remove the current element during iteration without an error. If you don't need entries, use ListQueue.
Modifying a queue while iterating
Like lists, queues detect changes during a for-in loop and throw ConcurrentModificationError. A work queue where processing an item can add more items should not iterate at all. Remove items one at a time until the queue is empty:
import 'dart:collection';
void main() {
final queue = Queue<int>.of([1, 2, 3]);
try {
for (final n in queue) {
if (n == 2) queue.add(4);
}
} on ConcurrentModificationError catch (e) {
print(e);
}
// Process items one at a time instead; new items are handled too.
final work = Queue<int>.of([1, 2, 3]);
while (work.isNotEmpty) {
final n = work.removeFirst();
if (n == 2) work.add(4);
print('processing $n');
}
}
Output:
Concurrent modification during iteration: Instance of 'ListQueue<int>'.
processing 1
processing 2
processing 3
processing 4
Priority queues
A priority queue always hands out the "smallest" element first, according to a comparator, regardless of insertion order. The SDK doesn't include one, but package:collection, maintained by the Dart team, has PriorityQueue, backed by a binary heap. Add it with dart pub add collection:
import 'package:collection/collection.dart';
class Job {
final String name;
final int priority; // lower number = more urgent
Job(this.name, this.priority);
@override
String toString() => '$name($priority)';
}
void main() {
final jobs = PriorityQueue<Job>((a, b) => a.priority.compareTo(b.priority))
..addAll([
Job('send newsletter', 5),
Job('fix outage', 1),
Job('reply to customer', 2),
Job('update docs', 5),
]);
print(jobs.first); // peek at the most urgent
jobs.add(Job('rotate keys', 0));
while (jobs.isNotEmpty) {
print(jobs.removeFirst());
}
// Natural order: a min-heap of ints.
final heap = PriorityQueue<int>()..addAll([7, 2, 9, 4]);
print(heap.toList()); // sorted copy; the queue is unchanged
print(heap.length);
}
Output:
fix outage(1)
rotate keys(0)
fix outage(1)
reply to customer(2)
send newsletter(5)
update docs(5)
[2, 4, 7, 9]
4
add and removeFirst are O(log n) and first is O(1). Without a comparator, elements must be Comparable. For a max-heap, reverse the comparator: (a, b) => b.compareTo(a).
A heap is not stable. The two jobs with priority 5 came out in insertion order here, but that's not guaranteed. If ties must be first-come, first-served, add an increasing sequence number and use it as a tie-breaker in the comparator (see Sorting for compound comparators).
An async queue
In async code you often want consumers to wait until an item is available instead of checking isEmpty. Two queues and a Completer are enough: one queue for items nobody has asked for yet, and one for consumers waiting for an item:
import 'dart:async';
import 'dart:collection';
/// A queue whose consumers can wait for the next item.
class AsyncQueue<T> {
final _items = Queue<T>();
final _waiting = Queue<Completer<T>>();
void add(T item) {
if (_waiting.isNotEmpty) {
_waiting.removeFirst().complete(item); // hand it straight over
} else {
_items.add(item);
}
}
Future<T> next() {
if (_items.isNotEmpty) return Future.value(_items.removeFirst());
final c = Completer<T>();
_waiting.add(c);
return c.future;
}
}
Future<void> worker(String name, AsyncQueue<int?> queue) async {
while (true) {
final job = await queue.next();
if (job == null) break; // stop signal
await Future.delayed(Duration(milliseconds: job));
print('$name finished ${job}ms job');
}
print('$name stopped');
}
Future<void> main() async {
final queue = AsyncQueue<int?>();
final workers = [worker('w1', queue), worker('w2', queue)];
for (final job in [300, 100, 150, 120]) {
queue.add(job);
}
queue
..add(null)
..add(null);
await Future.wait(workers);
}
Output:
w2 finished 100ms job
w2 finished 150ms job
w1 finished 300ms job
w1 stopped
w2 finished 120ms job
w2 stopped
Both workers start waiting before any job is added, so the first two jobs go straight to them. The rest wait in _items. The fast worker w2 handles three jobs while w1 is busy with the long one. Using a queue for the waiting consumers keeps it fair: whoever started waiting first gets the next item. See Returning a Future using a Completer and Async and Await for the building blocks.
If your items already come from a Stream, StreamQueue from package:async gives you the same "await the next item" API on top of it.
Choosing a structure
| Need | Use | Cost of key operations |
|---|---|---|
| Stack (LIFO) | List with add / removeLast / last |
O(1) |
| Queue (FIFO) | Queue() (a ListQueue) with add / removeFirst |
O(1) |
| Deque | ListQueue with addFirst / addLast / removeFirst / removeLast |
O(1) |
| Insert or remove next to a known node | DoubleLinkedQueue and its entries |
O(1) |
| Most urgent item first | PriorityQueue from package:collection |
O(log n) add and remove |
| Wait for the next item in async code | Queue + Completer, or StreamQueue |
O(1) |
Things to remember:
- Use the end of a
Listfor a stack, never the front. - Don't use
List.removeAt(0)as a queue for more than a few items. It's O(n) per call. - Empty
Listpops throwRangeError, emptyQueueremovals throwStateError. UseisEmpty,lastOrNullorfirstOrNullwhen empty is expected. Queueis anIterable, not aList: no[], noinsert, noreversed.- Drain a work queue with
while (q.isNotEmpty) q.removeFirst(), not withfor-in, if processing adds items.