What is a Queue
A queue is a collection that enforces a single rule: the first element added is the first one removed. This is called FIFO: First In, First Out.
Think of a line of people waiting at a counter. The first person to arrive is the first person served. Nobody cuts in front: new arrivals go to the back, and people leave from the front.
The waiting line analogy
Imagine a queue at a coffee shop. The first customer in line is served first. New customers join the back of the line. No matter how long the line gets, whoever has been waiting longest goes next.
In a queue, the element that has been in the collection the longest is always the next one out.
Unlike arrays and linked lists, a queue doesn't give you access to any arbitrary element. It exposes exactly two ends: you add to the rear and remove from the front.
A queue is an abstract data type (ADT), not a concrete data structure. It defines what operations are allowed and what rules they follow, but says nothing about how the data is stored in memory. Arrays and linked lists are concrete data structures: they describe a specific memory layout. A queue is a contract, and you can honor it with a circular array, a linked list, or anything else that supports enqueue and dequeue with FIFO semantics.
A queue is the mirror of a stack. A stack is LIFO (the last element in is the first out), and a queue is FIFO (the first element in is the first out). Both restrict the interface; they differ in the ordering rule.
The three operations
A queue's entire interface is three operations:
- enqueue: add an element to the rear
- dequeue: remove the element from the front
- peek: read the front element without removing it
There is no indexing, no searching and no insertion in the middle.
enqueue: adding to the rear
enqueue places a new element at the rear of the queue. Every enqueue increases the queue's size by one.
99 joins at the rear; 3 is still the front and will be next out
This is . You're always adding to the same place.
dequeue: removing from the front
dequeue removes the front element and returns it. The element behind it becomes the new front.
3 is removed, and 8 is now the front
Also . You're always removing from the same place.
peek: looking without touching
peek (sometimes called front) returns the front element without removing it. Use it when you need to check what's next before deciding whether to dequeue.
// After enqueue(3), enqueue(8), enqueue(17):// Queue: front → [3, 8, 17] ← rearpeek() → returns 3// Queue is still: front → [3, 8, 17] ← rearpeek is also .
Array-based implementation
The obvious approach is an array with a front index and a rear index: front points to the element to dequeue, and rear points to where the next enqueue lands.
The problem is that both indices only ever move forward. After enough enqueue and dequeue operations, rear reaches the end of the array even though the front portion is empty and wasted.
After 3 enqueues and 3 dequeues on a size-6 array:[ _, _, _, 7, 8, 9 ] ↑ ↑ wasted frontOne more enqueue moves rear out of bounds — but 3 slots are free!The solution is a circular buffer: wrap rear back to index 0 when it reaches the end, using the modulo operator. The array is treated as a ring.
#define MAX 100struct Queue { int data[MAX]; int front; int rear; int size;};void queue_init(struct Queue *q) { q->front = 0; q->rear = 0; q->size = 0;}int queue_is_empty(struct Queue *q) { return q->size == 0;}int queue_is_full(struct Queue *q) { return q->size == MAX;}Using size to track the count is cleaner than computing it from front and rear, because front == rear could mean either empty or full.
void enqueue(struct Queue *q, int value) { if (queue_is_full(q)) return; // queue overflow q->data[q->rear] = value; q->rear = (q->rear + 1) % MAX; // wrap around q->size++;}int dequeue(struct Queue *q) { if (queue_is_empty(q)) return -1; // queue underflow int value = q->data[q->front]; q->front = (q->front + 1) % MAX; // wrap around q->size--; return value;}int peek(struct Queue *q) { if (queue_is_empty(q)) return -1; return q->data[q->front];}The circular buffer reuses slots as the queue advances. The tradeoff is the fixed upper bound: you must know the maximum queue size in advance.
Linked-list-based implementation
A linked list removes the fixed-size constraint. Unlike the linked-list stack (which only needed a head pointer), a queue must track both ends: head is the front (dequeue), tail is the rear (enqueue).
Both operations remain O(1) because you always have a direct pointer to whichever end you need.
struct Node { int value; struct Node *next;};struct Queue { struct Node *head; // front — dequeue here struct Node *tail; // rear — enqueue here};void queue_init(struct Queue *q) { q->head = NULL; q->tail = NULL;}void enqueue(struct Queue *q, int value) { struct Node *node = malloc(sizeof(struct Node)); node->value = value; node->next = NULL; if (q->tail != NULL) q->tail->next = node; q->tail = node; if (q->head == NULL) q->head = node; // first element}int dequeue(struct Queue *q) { if (q->head == NULL) return -1; struct Node *temp = q->head; int value = temp->value; q->head = q->head->next; if (q->head == NULL) q->tail = NULL; // queue is now empty free(temp); return value;}int peek(struct Queue *q) { if (q->head == NULL) return -1; return q->head->value;}Choosing between implementations:
| Array-based (circular) | Linked-list-based | |
|---|---|---|
| Max size | Fixed at creation | Unlimited |
| Memory | Compact, cache-friendly | Scattered, pointer overhead |
| Overflow risk | Yes (bounded) | Only if memory is exhausted |
| Allocation | None (pre-allocated) | One malloc per enqueue |
| Complexity | Modulo arithmetic | Two-pointer management |
For small, bounded queues, such as a fixed-size event buffer or a producer-consumer ring buffer, the array version is simpler and faster in practice. For unbounded queues where the maximum size is unknown, use the linked list.
Try it yourself
Every operation below runs on two queues at once, one built on a circular array with room for six values and one built on a linked list with a head and a tail. These are the two implementations above. Dequeue a few times and then enqueue: rear reaches the last slot and wraps back to 0, reusing the slots front already left behind. Fill all six and the array overflows, while the list allocates one more node.
Keyboard and mouse
- Space
- play or pause
- ←→
- previous or next step
- HomeEnd
- start or end of the run
- <>
- slower or faster
- M
- sound on or off
- F
- fullscreen
- R
- reset
- Space+drag
- move the canvas
- Ctrl+scroll
- zoom
- every step of the next run shows up here
- every step of the next run shows up here
Common operations and their costs
| Operation | Time | Why |
|---|---|---|
| enqueue | O(1) | Always adds to the rear |
| dequeue | O(1) | Always removes from the front |
| peek | O(1) | Direct read of the front element |
| Search by value | O(n) | Must scan every element from front to rear |
| Access by position | O(n) | No index: must dequeue down to that level |
All three core operations are O(1), because only the front and the rear are accessible and the queue keeps a direct reference to both.
Queues in the real world
Print queues. The original use case that gave queues their name in computing. Every document sent to a printer joins a queue. The first document submitted is the first one printed. New jobs wait at the rear, and no job jumps ahead of one submitted before it.
Task scheduling. Operating system schedulers manage processes using queues. When multiple processes are ready to run, they wait in a queue. The CPU runs them one at a time in arrival order, giving each a time slice before moving to the next. Round-robin scheduling is a queue where dequeued processes re-enqueue after their slice.
Breadth-first search. Graph traversal using breadth-first search (BFS) uses a queue, where DFS uses a stack. When you reach a node, you enqueue its unvisited neighbors, then dequeue the next node to visit and repeat. The FIFO order means you explore every node at distance 1 before any at distance 2, and every node at distance 2 before any at distance 3. Shortest-path algorithms on unweighted graphs work this way.
// BFS explores layer by layer:// Start: [A]// Layer 1: [B, C] (neighbors of A)// Layer 2: [D, E, F] (neighbors of B and C)// Stack (DFS) would go deep; Queue (BFS) goes wide.Event queues. Every GUI framework, game loop, and network server processes events through a queue. Each mouse click, key press or incoming packet is enqueued as it arrives and dequeued in order when the program is ready to handle it. The queue decouples producers (the OS delivering events) from consumers (your application code) and smooths out bursts.
Producer-consumer. Queues are the standard solution to the producer-consumer problem, where one component produces work items faster or slower than another consumes them and the queue absorbs the difference. A web server enqueues incoming requests, and a pool of worker threads dequeues and handles them. Bursts wait in the queue, and both sides run at their own pace.
When Queues fall short
The same restrictions that keep every queue operation O(1) rule a queue out for some problems.
No random access. You can't reach the 3rd element without dequeueing the 1st and 2nd first. If you need to inspect or modify elements at arbitrary positions, a queue is the wrong structure.
FIFO only. Queues process elements in arrival order. If some elements are more urgent than others, like a high-priority process that should jump to the front, a plain queue can't express that. Use a priority queue instead, which orders elements by a priority key rather than arrival time.
Only two accessible ends. If your problem requires adding or removing at either end, like a sliding window that shrinks from both sides, use a deque (double-ended queue). A deque supports enqueue and dequeue at both front and rear.
Poor for search. Finding a specific value requires dequeueing everything ahead of it, which destroys the original queue order. Use a different structure when search is a primary operation.
Summary
Queues are the simplest fair structure you can put on a collection:
- FIFO: the first element in is always the first one out
- enqueue, dequeue and peek are all O(1)
- There are two implementations: a circular array (bounded, cache-friendly) or a linked list (unbounded, with a pointer to each end)
- A system that must process requests in arrival order, like a scheduler, uses a queue
- Breadth-first search uses a queue the same way DFS uses a stack
- An unconstrained structure lets callers reorder, skip and prioritize, so each caller has to handle ordering itself; a queue guarantees first come, first served
- Stacks and queues are the two basic orderings for processing sequential data: LIFO reverses it (undo, recursion, backtracking), and FIFO keeps arrival order (scheduling, BFS, buffering)