Intuition
A stack is a pile of plates: you put clean plates on top and take from the top, so the last plate added is the first used. A queue is a line at a shop: people join at the back and are served from the front, so the first to arrive is the first to leave.
Both hold items in the order they arrived. The only difference is which end you take from.
How it works
| Operation | Stack | Queue |
|---|---|---|
| Add | push: put on top |
enqueue: join at the back |
| Remove | pop: take from the top |
dequeue: leave from the front |
| Look without removing | peek the top |
peek the front |
| Order out | Last in, first out (LIFO) | First in, first out (FIFO) |
A stack fits neatly on a dynamic array: push and pop both work at the end, which costs O(1). A queue needs both ends. Removing from the front of an array shifts everything, O(n), so real queues use a deque (a ring buffer or linked blocks) where both ends are O(1).
Common mistakes
- Using an array’s front as a queue.
list.pop(0)in Python andshift()in JavaScript are O(n). On large queues, usecollections.dequeor a ring buffer. - Popping an empty stack. Check the size first; the error (or
undefined, or a panic) depends on the language. - Picking the wrong one. If the newest work matters most (undo, nested calls, depth-first search), you want a stack. If fairness or arrival order matters (tasks, breadth-first search), you want a queue.
In other languages
| Language | Stack | Queue |
|---|---|---|
| Python | list (append, pop) |
collections.deque (append, popleft) |
| JavaScript | Array (push, pop) |
None built in; Array works for small queues |
| Java | ArrayDeque (push, pop) |
ArrayDeque (offer, poll) |
| C | Write your own | Write your own |
| Go | Slice (append, reslice) |
Slice, or container/list |
| Rust | Vec (push, pop) |
VecDeque (push_back, pop_front) |
Try it yourself
Push and pop your own values:
step 1 / 1changingtop
Now the same with a queue. Notice which value each one gives back:
step 1 / 1changingfront
Check yourself
Check yourself
Push 1, 2 and 3 onto a stack, then pop twice. What is left?
The pops remove 3, then 2. Only 1, the first value pushed, is left.
Check yourself
Enqueue 1, 2 and 3, then dequeue once. What is now at the front?
The dequeue removes 1, the oldest value, so 2 is now at the front.
Sources
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, section 10.1, “Stacks and queues” (3rd edition).
Finished this page?
Your list