D
DSA in DartEasy20 XP3 min read

How do you implement a stack and queue in Dart?

TL;DR: Stack (LIFO): use List with add/removeLast. Queue (FIFO): use dart:collection Queue with addLast/removeFirst. Both O(1) for add/remove. Stack is used for undo/redo, navigation history; Queue for BFS and task scheduling.

Full Answer

Stack and Queue are fundamental data structures with opposite insertion/removal patterns. Both appear in Flutter: Navigator uses a stack, BFS traversal uses a queue.

AspectStack (LIFO)Queue (FIFO)
OrderLast In, First OutFirst In, First Out
Addpush (add to top)enqueue (add to back)
Removepop (from top)dequeue (from front)
DartList.add() / removeLast()Queue.addLast() / removeFirst()
๐ŸŽฏ

Flutter's Navigator is a stack of routes: Navigator.push() adds to the top, Navigator.pop() removes from the top. Understanding this makes navigation debugging intuitive.

Code Examples

dartStack and Queue implementations
Output
3
A
true
false

Common Mistakes

  • โœ—Using List.removeAt(0) for a queue โ€” O(n) instead of Queue.removeFirst() which is O(1)
  • โœ—Calling pop/peek on an empty stack โ€” throws RangeError; always check isEmpty first

Interview Tip

๐Ÿ’ก

Balanced parentheses is the canonical stack interview question. Undo/redo in a text editor is another. BFS of a widget tree uses a queue โ€” these real-world connections impress interviewers.

#stack#queue#LIFO#FIFO#data-structures