Chapter 7: Queues
Introduction
Learning Outcomes
Model a queue as Q = {a0, …, an−1} and identify its front and rear.
Explain why cells freed at the front can't be reused, and what shifting costs.
Wrap around with % MAX and tell full from empty in three ways.
Enqueue and dequeue in O(1) with front and rear pointers.
Implement a double-ended queue, with insertion and removal at both ends, in a circular array.
Use a queue in a time-sliced job scheduling simulation; build a queue from two stacks.
The Queue ADT
The Queue: First In, First Out
In a queue Q = {a0, a1, …, an−1}, unlike a stack, the first item to be processed is a0 (the front); an−1 sits at the rear. Items are inserted at the rear and deleted at the front: FIFO (first-in-first-out).
Empty queue: front and rear at the same place.
A added at the rear.
B added at the rear.
C added at the rear.
D added at the rear.
The first one out is A, the first one in: FIFO. The front cell is now free.
The Queue ADT
Abstract Data Type: Queue
| Operation | Meaning | Error case |
|---|---|---|
queue_create(max) | Empty queue for at most max items | — |
queue_full(Q) | True if no room is left | — |
enqueue(Q, x) | Adds x at the rear | Overflow if full |
queue_empty(Q) | True if it holds no items | — |
dequeue(Q) | Removes and returns the front item | Underflow if empty |
queue_front(Q) · peek | Reads the front item without removing it | Error if empty |
One end: push and pop at the top. LIFO.
Two ends: insert at the rear, remove at the front. FIFO.
The Queue ADT
Where Queues Show Up
Ready processes, print jobs, and disk requests wait their turn in queues.
Keyboard input, network packets, audio streams: a circular buffer between producer and consumer.
BFS and level-order tree traversal: the children of the current node go to the rear, the next node comes from the front.
Bank tellers, traffic lights, job scheduling: arriving customers join the line.
Servers hand off work in order, without losing any.
Called a “queue” but not FIFO: the highest-priority item leaves first.
The Queue ADT
Add at the Rear, Remove at the Front
Items leave in the same order they arrived. With a stack it was the reverse.
Linear Queue
Linear Queue in an Array
#define MAX_QUEUE_SIZE 100 element queue[MAX_QUEUE_SIZE]; int front = -1; /* one before the first item */ int rear = -1; /* last item */ void enqueue(int *rear, element item) { if (*rear >= MAX_QUEUE_SIZE - 1) /* any room? */ queue_full(); /* warn and exit */ queue[++*rear] = item; /* bump, then store */ } element dequeue(int *front, int rear) { if (*front == rear) queue_empty(); /* warn and exit if empty */ return queue[++*front]; /* bump, return the front */ }
frontpoints one before the first item, not at it;rearpoints at the last item.- Empty: front == rear (both −1 at the start).
- Full: rear == MAX − 1, even if there is room at the front.
dequeuedoesn't changerear, so it takes it by value.queue_full/queue_empty: print a message andexit, as with the stack.
Linear Queue · Run the code step by step
Code Trace: the Linear Queue and “False Fullness”
Initially front = rear = −1: the queue is empty. MAX_QUEUE_SIZE = 4. Enqueue A, B, C; dequeue twice; enqueue D, E.
-1 ≥ 3? No.
++*rear → 0; queue[0] = A.
0 ≥ 3? No.
++*rear → 1; queue[1] = B.
1 ≥ 3? No.
++*rear → 2; queue[2] = C.
front == rear (-1 == 2)? No, not empty.
++*front → 0; queue[0] = A is returned. The cell is no longer used.
front == rear (0 == 2)? No, not empty.
++*front → 1; queue[1] = B is returned. The cell is no longer used.
2 ≥ 3? No.
++*rear → 3; queue[3] = D.
3 ≥ 3 → counted as full! Yet cells 0 and 1 are empty.
queue_full(): the program ends. The linear queue's flaw: once rear hits the end, the free cells at the front can't be used.
void enqueue(int *rear, element item) { if (*rear >= MAX_QUEUE_SIZE - 1) queue_full(); /* "Queue is full!!!", exit */ queue[++*rear] = item; } element dequeue(int *front, int rear) { if (*front == rear) queue_empty(); /* "Queue is empty!!!", exit */ return queue[++*front]; }
Linear Queue
Free Space at the Front: Shift Everything?
Two cells are free at the front, but rear has hit the end.
Shifting moves each of the n items once → O(n).
Room is made, but doing this on every “full” makes enqueue O(n).
Shifting takes far too long, so the circular queue was devised: join the end of the array to its start, and the cells freed at the front get reused as if they were at the rear.
Circular Queue
Circular Queue
- Think of the array's end as joined to its start: after 5 comes 0.
- Advance:
rear = (rear + 1) % MAX,front = (front + 1) % MAX. frontstill points one before the first item; initiallyfront = rear = 0.- Empty: front == rear. Full: (rear + 1) % MAX == front.
- So one of the MAX cells always stays empty: at most MAX − 1 items.
Circular Queue
Wrap-Around: % MAX
| rear | rear + 1 | (rear + 1) % 6 | Meaning |
|---|---|---|---|
| 3 | 4 | 4 | normal step |
| 4 | 5 | 5 | last cell |
| 5 | 6 | 0 | wrap: back to the start |
| 0 | 1 | 1 | normal again |
One step back: (i − 1 + MAX) % MAX. In C, -1 % 6 is −1; adding MAX keeps the result non-negative (the deque uses this).
(rear − front + MAX) % MAX. Example: front = 4, rear = 1, MAX = 6 → (1 − 4 + 6) % 6 = 3.
Circular Queue
Circular Queue in Pictures: Wrapping with A…F
Empty queue: front == rear = 0.
A added: rear = 1.
B added: rear = 2.
C added: rear = 3.
D added: rear = 4.
E added: rear = 5.
A removed: front = 1. Cells 0 and 1 are now both free.
F goes to rear = (5 + 1) % 6 = 0: the cell freed at the front is reused as if it were at the rear. The queue is now full: (0 + 1) % 6 == front. 5 items in 6 cells.
Circular Queue
Circular Queue: C Code
void enqueue(int front, int *rear, element item) { *rear = (*rear + 1) % MAX_QUEUE_SIZE; /* advance */ if (front == *rear) queue_full(); /* full? */ queue[*rear] = item; /* store */ } element dequeue(int *front, int rear) { if (*front == rear) queue_empty(); /* empty? */ *front = (*front + 1) % MAX_QUEUE_SIZE; /* advance */ return queue[*front]; /* return */ }
enqueue advances *rear first and checks for fullness afterwards. Since queue_full ends the program, that's harmless here; but in a version that returns an error, rear is left corrupted (equal to front, so the queue looks empty). The safe version tries the new position in a temporary first (Horowitz–Sahni also roll rear back).Circular Queue · Run the code step by step
Code Trace: a Safe Circular Queue
MAX_QUEUE_SIZE = 5, front = rear = 0. Enqueue A, B, C, D, E; dequeue twice; enqueue E, F, G.
next = (0 + 1) % 5 = 1; 1 ≠ front, there is room.
rear = 1, queue[1] = A.
next = (1 + 1) % 5 = 2; 2 ≠ front, there is room.
rear = 2, queue[2] = B.
next = (2 + 1) % 5 = 3; 3 ≠ front, there is room.
rear = 3, queue[3] = C.
next = (3 + 1) % 5 = 4; 4 ≠ front, there is room.
rear = 4, queue[4] = D.
next = (4 + 1) % 5 = 0 == front → full, returns false. rear stays 4. 4 items in 5 cells.
front == rear (0 == 4)? No.
front = 1, *x = queue[1] = A.
front == rear (1 == 4)? No.
front = 2, *x = queue[2] = B.
next = (4 + 1) % 5 = 0 (wrap!); 0 ≠ front, there is room.
rear = 0, queue[0] = E.
next = (0 + 1) % 5 = 1; 1 ≠ front, there is room.
rear = 1, queue[1] = F.
next = (1 + 1) % 5 = 2 == front → full, returns false. rear stays 1. 4 items in 5 cells.
bool enqueue(int front, int *rear, element x) { int next = (*rear + 1) % MAX_QUEUE_SIZE; if (next == front) return false; /* full */ *rear = next; queue[next] = x; return true; } bool dequeue(int *front, int rear, element *x) { if (*front == rear) return false; /* empty */ *front = (*front + 1) % MAX_QUEUE_SIZE; *x = queue[*front]; return true; }
Circular Queue
Telling Full from Empty: Three Methods
| Method | Empty | Full | Capacity | Cost |
|---|---|---|---|---|
| 1. Leave one cell empty | front == rear | (rear+1)%MAX == front | MAX − 1 | One wasted cell |
| 2. Keep a count | count == 0 | count == MAX | MAX | Update the count on every operation |
| 3. Keep a flag | front == rear and last op was dequeue | front == rear and last op was enqueue | MAX | A flag on every operation |
The root of the problem: with only front and rear we want to distinguish MAX + 1 fill levels (0, 1, …, MAX items), but the difference of two indices takes only MAX distinct values. Either give up one state (method 1) or keep extra information (methods 2 and 3).
rear at all: rear = (front + count − 1) % CAP.Circular Queue · Run the code step by step
Code Trace: a Circular Queue with a Count
CAP = 3, front = 0, count = 0. Enqueue 1, 2, 3, 4; dequeue; enqueue 4; dequeue.
There is room; pos = (front + count) % 3 = 0, data[0] = 1; count = 1.
There is room; pos = (front + count) % 3 = 1, data[1] = 2; count = 2.
There is room; pos = (front + count) % 3 = 2, data[2] = 3; count = 3.
count == CAP → full. All three cells are in use: no cell is wasted.
Not empty; *x = data[0] = 1.
front = 1, count = 2.
There is room; pos = (front + count) % 3 = 0 (wrap), data[0] = 4; count = 3.
Not empty; *x = data[1] = 2.
front = 2, count = 2.
bool enqueue(Queue *q, int x) { if (q->count == CAP) return false; /* full */ q->data[(q->front + q->count) % CAP] = x; q->count++; return true; } bool dequeue(Queue *q, int *x) { if (q->count == 0) return false; /* empty */ *x = q->data[q->front]; q->front = (q->front + 1) % CAP; q->count--; return true; }
Linked Queue
A Queue as a Linked List
front points to the first node, rear to the last; the last node's link is NULL.
- Insert at the rear:
rear->link = new_node; rear = new_node;→ O(1). - Delete at the front:
front = front->link;→ O(1). - Not the other way round (insert at the front, delete at the rear): in a singly linked list, deleting the last node means finding the one before it, which is O(n).
Linked Queue · Run the code step by step
Code Trace: Linked enqueue
Empty queue: front = rear = NULL. Enqueue 10, 20, 30 in turn.
malloc: a new node is allocated.
data = 10, link = NULL (it will be the new last node).
*rear == NULL: the queue was empty, so the new node is also the front: *front = new_node.
*rear = new_node: rear points to 10.
malloc: a new node is allocated.
data = 20, link = NULL (it will be the new last node).
The queue is not empty: (*rear)->link = new_node, so 10 now points to 20.
*rear = new_node: rear points to 20.
malloc: a new node is allocated.
data = 30, link = NULL (it will be the new last node).
The queue is not empty: (*rear)->link = new_node, so 20 now points to 30.
*rear = new_node: rear points to 30.
Queue: 10 → 20 → 30. Each enqueue does constant work: O(1); without rear, finding the end would be O(n).
bool enqueue(node **front, node **rear, int x) { node *new_node = malloc(sizeof *new_node); if (new_node == NULL) return false; new_node->data = x; new_node->link = NULL; if (*rear == NULL) *front = new_node; /* empty queue */ else (*rear)->link = new_node; /* link at end */ *rear = new_node; return true; }
Linked Queue · Run the code step by step
Code Trace: Linked dequeue
Queue: 10 → 20. Call dequeue three times.
old = *front.
*x = 10; *front = old->link → node(20).
*front ≠ NULL: rear is unchanged.
free(old); main prints 10.
old = *front.
*x = 20; *front = old->link → NULL.
*front == NULL: the last item is gone too; without *rear = NULL, rear would keep pointing to a node about to be freed (a dangling pointer)!
free(old); main prints 20.
old == NULL → empty, returns false.
bool dequeue(node **front, node **rear, int *x) { node *old = *front; if (old == NULL) return false; /* empty */ *x = old->data; *front = old->link; if (*front == NULL) *rear = NULL; /* last one gone */ free(old); return true; }
Linked Queue
Comparing Queue Implementations
| Criterion | Linear array | Circular array | Linked list |
|---|---|---|---|
| enqueue / dequeue | O(1), but “false full” | O(1) | O(1) (malloc/free) |
| Shifting needed? | Yes: O(n) | No | No |
| Capacity | MAX | MAX − 1 (or MAX with a count) | Up to available memory |
| Extra memory | None | None | One pointer per item |
| Special case | front/rear hit the end | Wrap-around and full/empty test | rear = NULL when emptied |
In practice the circular array (a fixed-capacity buffer) and the growable circular array are the most common; a linked queue is preferred when the items already live as nodes or the maximum size is unknown.
Deques and Applications
The Double-Ended Queue (Deque)
- Deque (double-ended queue): insertion and deletion at both ends, all in O(1).
- Use only one end and it is a stack; insert at one end and remove at the other and it is a queue.
- Restricted variants: input-restricted (insert at one end only) and output-restricted (delete at one end only).
- Uses: sliding-window maximum, work stealing, undo + redo history.
Deques and Applications · Run the code step by step
Code Trace: a Deque in a Circular Array
CAP = 5; push_back has stored 10 and 20. Now push 5 and 3 at the front, then pop the back twice.
count = 2 < 5, there is room.
front = (0 − 1 + 5) % 5 = 4: one step back from 0 is the end of the array.
data[4] = 5; count = 3.
count = 3 < 5, there is room.
front = (4 − 1 + 5) % 5 = 3.
data[3] = 3; count = 4.
Last position = (3 + 4 − 1) % 5 = 1; *x = 20.
count = 3. (front is unchanged.)
Last position = (3 + 3 − 1) % 5 = 0; *x = 10.
count = 2. (front is unchanged.)
bool push_front(Deque *d, int x) { if (d->count == CAP) return false; d->front = (d->front - 1 + CAP) % CAP; /* one back */ d->data[d->front] = x; d->count++; return true; } bool pop_back(Deque *d, int *x) { if (d->count == 0) return false; *x = d->data[(d->front + d->count - 1) % CAP]; d->count--; return true; }
Deques and Applications
Several Queues in One Array
As with multiple stacks, a one-dimensional memory[] array is split into segments, and each queue keeps its own front[i], rear[i], and boundary[i].
The stack trick of growing from the two ends doesn't work for queues: a queue moves at both of its ends and drifts within its segment.
Managing each segment as its own circular queue avoids shifting, but when a segment fills up, room still has to be made (O(m)).
Usually each queue gets its own growable array or linked list.
Deques and Applications · Run the code step by step
Code Trace: Round-Robin Scheduling
Three processes need P0 = 5, P1 = 2, P2 = 4 units of work. Time slice Q = 2 (round robin).
P0 is taken from the front and runs 2 units; t = 2.
P0 has 3 units left → goes back to the rear.
P1 is taken from the front and runs 2 units; t = 4.
P1 is finished; it doesn't rejoin the queue.
P2 is taken from the front and runs 2 units; t = 6.
P2 has 2 units left → goes back to the rear.
P0 is taken from the front and runs 2 units; t = 8.
P0 has 1 unit left → goes back to the rear.
P2 is taken from the front and runs 2 units; t = 10.
P2 is finished; it doesn't rejoin the queue.
P0 is taken from the front and runs 1 unit; t = 11.
P0 is finished; it doesn't rejoin the queue.
/* q: queue of process ids; Q: time slice */ while (dequeue(&q, &p)) { int run = left[p] < Q ? left[p] : Q; time += run; left[p] -= run; if (left[p] > 0) enqueue(&q, p); /* back of line */ else printf("P%d done: t=%d\n", p, time); }
Deques and Applications · Run the code step by step
Code Trace: a Queue Built from Two Stacks
The queue is made of two stacks. Enqueue 1, 2, 3; dequeue; enqueue 4; dequeue three times.
enqueue(1): push onto the in stack, O(1).
enqueue(2): push onto the in stack, O(1).
enqueue(3): push onto the in stack, O(1).
The out stack is empty → transfer everything from the in stack.
Pop 3 from in, push it onto out.
Pop 2 from in, push it onto out.
Pop 1 from in, push it onto out.
The top of the out stack is 1, the oldest item. FIFO achieved.
enqueue(4): push onto the in stack, O(1).
The top of the out stack is 2, the oldest item. FIFO achieved.
The top of the out stack is 3, the oldest item. FIFO achieved.
The out stack is empty → transfer everything from the in stack.
Pop 4 from in, push it onto out.
The top of the out stack is 4, the oldest item. FIFO achieved. Each item is transferred at most once → amortized O(1).
void enqueue(Queue2 *q, int x) { push(&q->in, x); } bool dequeue(Queue2 *q, int *x) { int t; if (stack_empty(&q->out)) /* out is empty */ while (pop(&q->in, &t)) /* move them all */ push(&q->out, t); return pop(&q->out, x); }
Deques and Applications
Which One Fits?
| Problem | Structure |
|---|---|
| Documents sent to a printer | showQueue: printed in the order they were sent. |
| Ctrl+Z in a text editor | showStack: the most recent action is undone first. |
| Printing a tree level by level | showQueue (BFS). |
| Checking nested parentheses | showStack: each closing bracket matches the most recently opened one. |
| Function calls | showStack (the call stack). |
| Sickest patient first in the ER | showPriority queue: not FIFO! |
Lab · C code step by step
Lab: Circular Queue
Summary
Complexity Summary
| Operation | Linear array | Circular array | Linked | Deque (circular) |
|---|---|---|---|---|
| enqueue | O(1)* | O(1) | O(1) | O(1) at both ends |
| dequeue | O(1) | O(1) | O(1) | O(1) at both ends |
| front / empty / full | O(1) | O(1) | O(1) | O(1) |
| item count | rear − front | (rear−front+MAX)%MAX | O(n) or a count | count |
| memory | MAX | MAX | n · (item + pointer) | CAP |
* Enqueue in a linear queue is O(1), but O(n) if it shifts on a “false full.” The round-robin simulation and level-order traversal perform O(n) queue operations for n items.
Summary
Common Mistakes
rear == MAX−1 in a linear queue as truly full.% MAX in a circular queue and writing past the array.rear first and not rolling it back when full: the queue then looks empty.(i − 1) % MAX to step back: in C the result can be negative.rear = NULL when the last item leaves a linked queue.front on the first insert into an empty queue.Summary
Exercises
- MAX = 6, front = 4, rear = 1: how many items are there, and at which indices?
- Write
enqueueanddequeuefor a circular queue that uses the flag method. - Build a queue from two stacks. What is the amortized cost of
dequeue? - Implement a queue as a circular linked list with only a rear pointer.
- Run the round-robin example with Q = 3: when does each process finish?
Hints / answers
- (1 − 4 + 6) % 6 = 3 items: indices 5, 0, 1 (from just after front up to rear).
- Empty: front == rear && !last_was_enq; full: front == rear && last_was_enq. enqueue sets the flag to 1, dequeue to 0.
- Push onto the in stack; in dequeue, if the out stack is empty, move the whole in stack over, then pop. Each item moves at most twice → amortized O(1).
- rear->link is the front node. Enqueue: new_node->link = rear->link; rear->link = new_node; rear = new_node. Dequeue: front = rear->link.
- P0: 0–3, P1: 3–5 (done at t=5), P2: 5–8, P0: 8–10 (done at t=10), P2: 10–11 (done at t=11).
Summary
Chapter Summary
Insert at the rear, remove at the front; first in, first out.
Simple, but once rear hits the end the free space at the front is lost; shifting is expensive.
Wrap with % MAX; empty: front == rear, full: (rear+1)%MAX == front.
Leave one cell empty, or keep a count or a flag.
front and rear pointers; rear = NULL when the last item leaves.
Deques, job scheduling, buffers, a queue from two stacks, BFS.
Summary
References and Next Steps
- E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Sections 3.3 and 4.3.
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., Section 10.1 (queues, deque exercises).
- R. Sedgewick, Algorithms in C, Parts 1–4, Chapter 4.