Chapter 7: Queues

Data Structures and Algorithms with C
FIFOQueue ADTLinear queueCircular queueLinked queueDequeSchedulingBFS
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Define FIFO

Model a queue as Q = {a0, …, an−1} and identify its front and rear.

See the linear queue's flaw

Explain why cells freed at the front can't be reused, and what shifting costs.

Write a circular queue

Wrap around with % MAX and tell full from empty in three ways.

Build a linked queue

Enqueue and dequeue in O(1) with front and rear pointers.

Know the deque

Implement a double-ended queue, with insertion and removal at both ends, in a circular array.

Apply queues

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).

front →← rearempty queue

Empty queue: front and rear at the same place.

Afront →← rearA added

A added at the rear.

ABfront →← rearB added

B added at the rear.

ABCfront →← rearC added

C added at the rear.

ABCDfront →← rearD added

D added at the rear.

BCDfront →← rearA removed

The first one out is A, the first one in: FIFO. The front cell is now free.

The Queue ADT

Abstract Data Type: Queue

OperationMeaningError 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 rearOverflow if full
queue_empty(Q)True if it holds no items—
dequeue(Q)Removes and returns the front itemUnderflow if empty
queue_front(Q) · peekReads the front item without removing itError if empty
Stack

One end: push and pop at the top. LIFO.

Queue

Two ends: insert at the rear, remove at the front. FIFO.

The Queue ADT

Where Queues Show Up

Operating systems

Ready processes, print jobs, and disk requests wait their turn in queues.

Buffers

Keyboard input, network packets, audio streams: a circular buffer between producer and consumer.

Breadth-first search

BFS and level-order tree traversal: the children of the current node go to the rear, the next node comes from the front.

Simulation

Bank tellers, traffic lights, job scheduling: arriving customers join the line.

Message queues

Servers hand off work in order, without losing any.

Priority queue

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 */
}
  • front points one before the first item, not at it; rear points at the last item.
  • Empty: front == rear (both −1 at the start).
  • Full: rear == MAX − 1, even if there is room at the front.
  • dequeue doesn't change rear, so it takes it by value.
  • queue_full/queue_empty: print a message and exit, as with the stack.

Linear Queue · Run the code step by step

Code Trace: the Linear Queue and “False Fullness”

0123-1▲ front = -1▲ rear = -1

Initially front = rear = −1: the queue is empty. MAX_QUEUE_SIZE = 4. Enqueue A, B, C; dequeue twice; enqueue D, E.

0123-1▲ front = -1▲ rear = -1

-1 ≥ 3? No.

0A123-1▲ front = -1▲ rear = 0

++*rear → 0; queue[0] = A.

0A123-1▲ front = -1▲ rear = 0

0 ≥ 3? No.

0A1B23-1▲ front = -1▲ rear = 1

++*rear → 1; queue[1] = B.

0A1B23-1▲ front = -1▲ rear = 1

1 ≥ 3? No.

0A1B2C3-1▲ front = -1▲ rear = 2

++*rear → 2; queue[2] = C.

0A1B2C3-1▲ front = -1▲ rear = 2

front == rear (-1 == 2)? No, not empty.

0A1B2C3-1▲ front = 0▲ rear = 2

++*front → 0; queue[0] = A is returned. The cell is no longer used.

0A1B2C3-1▲ front = 0▲ rear = 2

front == rear (0 == 2)? No, not empty.

0A1B2C3-1▲ front = 1▲ rear = 2

++*front → 1; queue[1] = B is returned. The cell is no longer used.

0A1B2C3-1▲ front = 1▲ rear = 2

2 ≥ 3? No.

0A1B2C3D-1▲ front = 1▲ rear = 3

++*rear → 3; queue[3] = D.

0A1B2C3D-1▲ front = 1▲ rear = 3

3 ≥ 3 → counted as full! Yet cells 0 and 1 are empty.

0A1B2C3D-1▲ front = 1▲ rear = 3

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?

012C3Dfront = 1, rear = 3: “full”

Two cells are free at the front, but rear has hit the end.

012C3Dshift every item to the start

Shifting moves each of the n items once → O(n).

0C1D23front = −1, rear = 1

Room is made, but doing this on every “full” makes enqueue O(n).

Instructor “Shifting! The worst word in computer science! It means high cost!”

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

0frontA1B2C3rear45
  • Think of the array's end as joined to its start: after 5 comes 0.
  • Advance: rear = (rear + 1) % MAX, front = (front + 1) % MAX.
  • front still points one before the first item; initially front = 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

rearrear + 1(rear + 1) % 6Meaning
344normal step
455last cell
560wrap: back to the start
011normal again
Stepping back

One step back: (i − 1 + MAX) % MAX. In C, -1 % 6 is −1; adding MAX keeps the result non-negative (the deque uses this).

Item count

(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

0frontrear12345012345front = 0 rear = 0start: front = rear = 0

Empty queue: front == rear = 0.

0frontA1rear234501A2345front = 0 rear = 1A added

A added: rear = 1.

0frontA1B2rear34501A2B345front = 0 rear = 2B added

B added: rear = 2.

0frontA1B2C3rear4501A2B3C45front = 0 rear = 3C added

C added: rear = 3.

0frontA1B2C3D4rear501A2B3C4D5front = 0 rear = 4D added

D added: rear = 4.

0frontA1B2C3D4E5rear01A2B3C4D5Efront = 0 rear = 5E added

E added: rear = 5.

01frontB2C3D4E5rear012B3C4D5Efront = 1 rear = 5A removed

A removed: front = 1. Cells 0 and 1 are now both free.

F0rear1frontB2C3D4E50F12B3C4D5Efront = 1 rear = 0F added: rear 5 → 0 (wrap)

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 */
}
A subtle point: 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).
Instructor “Which is the best university in the world for computer engineering? Harvard? Then you should study as if you were thinking, ‘I'm at Harvard, and if I fail I'll be kicked out and have to go to a worse school.’”

Circular Queue · Run the code step by step

Code Trace: a Safe Circular Queue

0frontrear123401234front = 0 rear = 0count = (0 − 0 + 5) % 5 = 0

MAX_QUEUE_SIZE = 5, front = rear = 0. Enqueue A, B, C, D, E; dequeue twice; enqueue E, F, G.

0frontrear123401234front = 0 rear = 0count = (0 − 0 + 5) % 5 = 0next = 1

next = (0 + 1) % 5 = 1; 1 ≠ front, there is room.

0frontA1rear23401A234front = 0 rear = 1count = (1 − 0 + 5) % 5 = 1

rear = 1, queue[1] = A.

0frontA1rear23401A234front = 0 rear = 1count = (1 − 0 + 5) % 5 = 1next = 2

next = (1 + 1) % 5 = 2; 2 ≠ front, there is room.

0frontA1B2rear3401A2B34front = 0 rear = 2count = (2 − 0 + 5) % 5 = 2

rear = 2, queue[2] = B.

0frontA1B2rear3401A2B34front = 0 rear = 2count = (2 − 0 + 5) % 5 = 2next = 3

next = (2 + 1) % 5 = 3; 3 ≠ front, there is room.

0frontA1B2C3rear401A2B3C4front = 0 rear = 3count = (3 − 0 + 5) % 5 = 3

rear = 3, queue[3] = C.

0frontA1B2C3rear401A2B3C4front = 0 rear = 3count = (3 − 0 + 5) % 5 = 3next = 4

next = (3 + 1) % 5 = 4; 4 ≠ front, there is room.

0frontA1B2C3D4rear01A2B3C4Dfront = 0 rear = 4count = (4 − 0 + 5) % 5 = 4

rear = 4, queue[4] = D.

0frontA1B2C3D4rear01A2B3C4Dfront = 0 rear = 4count = (4 − 0 + 5) % 5 = 4next = 0

next = (4 + 1) % 5 = 0 == front → full, returns false. rear stays 4. 4 items in 5 cells.

0frontA1B2C3D4rear01A2B3C4Dfront = 0 rear = 4count = (4 − 0 + 5) % 5 = 4

front == rear (0 == 4)? No.

01frontB2C3D4rear012B3C4Dfront = 1 rear = 4count = (4 − 1 + 5) % 5 = 3

front = 1, *x = queue[1] = A.

01frontB2C3D4rear012B3C4Dfront = 1 rear = 4count = (4 − 1 + 5) % 5 = 3

front == rear (1 == 4)? No.

012frontC3D4rear0123C4Dfront = 2 rear = 4count = (4 − 2 + 5) % 5 = 2

front = 2, *x = queue[2] = B.

012frontC3D4rear0123C4Dfront = 2 rear = 4count = (4 − 2 + 5) % 5 = 2next = 0

next = (4 + 1) % 5 = 0 (wrap!); 0 ≠ front, there is room.

E0rear12frontC3D40E123C4Dfront = 2 rear = 0count = (0 − 2 + 5) % 5 = 3

rear = 0, queue[0] = E.

E0rear12frontC3D40E123C4Dfront = 2 rear = 0count = (0 − 2 + 5) % 5 = 3next = 1

next = (0 + 1) % 5 = 1; 1 ≠ front, there is room.

E0F1rear2frontC3D40E1F23C4Dfront = 2 rear = 1count = (1 − 2 + 5) % 5 = 4

rear = 1, queue[1] = F.

E0F1rear2frontC3D40E1F23C4Dfront = 2 rear = 1count = (1 − 2 + 5) % 5 = 4next = 2

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

MethodEmptyFullCapacityCost
1. Leave one cell emptyfront == rear(rear+1)%MAX == frontMAX − 1One wasted cell
2. Keep a countcount == 0count == MAXMAXUpdate the count on every operation
3. Keep a flagfront == rear and last op was dequeuefront == rear and last op was enqueueMAXA 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).

The counted version also gives the size in O(1) and doesn't store rear at all: rear = (front + count − 1) % CAP.

Circular Queue · Run the code step by step

Code Trace: a Circular Queue with a Count

012▲ frontcount = 0CAP = 3

CAP = 3, front = 0, count = 0. Enqueue 1, 2, 3, 4; dequeue; enqueue 4; dequeue.

0112▲ frontcount = 1CAP = 3

There is room; pos = (front + count) % 3 = 0, data[0] = 1; count = 1.

01122▲ frontcount = 2CAP = 3

There is room; pos = (front + count) % 3 = 1, data[1] = 2; count = 2.

011223▲ frontcount = 3CAP = 3

There is room; pos = (front + count) % 3 = 2, data[2] = 3; count = 3.

011223▲ frontcount = 3CAP = 3

count == CAP → full. All three cells are in use: no cell is wasted.

011223▲ frontcount = 3CAP = 3

Not empty; *x = data[0] = 1.

01223▲ frontcount = 2CAP = 3

front = 1, count = 2.

041223▲ frontcount = 3CAP = 3

There is room; pos = (front + count) % 3 = 0 (wrap), data[0] = 4; count = 3.

041223▲ frontcount = 3CAP = 3

Not empty; *x = data[1] = 2.

04123▲ frontcount = 2CAP = 3

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*rear102030NULL

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).
Instructor “– What have I been teaching for two lectures? I put the course aside and taught C, taught pointers. Pointers everyone supposedly knows so well, I taught them too. – I know pointers very well, but when the professor says something, I still don't get it. – That can happen.”

Linked Queue · Run the code step by step

Code Trace: Linked enqueue

*frontNULL*rearNULL

Empty queue: front = rear = NULL. Enqueue 10, 20, 30 in turn.

*frontNULL*rearNULL?NULLnew_node

malloc: a new node is allocated.

*frontNULL*rearNULL10NULLnew_node

data = 10, link = NULL (it will be the new last node).

*front*rearNULL10NULLnew_node

*rear == NULL: the queue was empty, so the new node is also the front: *front = new_node.

*front*rear10NULLnew_node

*rear = new_node: rear points to 10.

*front*rear10?NULLnew_node

malloc: a new node is allocated.

*front*rear1020NULLnew_node

data = 20, link = NULL (it will be the new last node).

*front*rear1020NULLnew_node

The queue is not empty: (*rear)->link = new_node, so 10 now points to 20.

*front*rear1020NULLnew_node

*rear = new_node: rear points to 20.

*front*rear1020?NULLnew_node

malloc: a new node is allocated.

*front*rear102030NULLnew_node

data = 30, link = NULL (it will be the new last node).

*front*rear102030NULLnew_node

The queue is not empty: (*rear)->link = new_node, so 20 now points to 30.

*front*rear102030NULLnew_node

*rear = new_node: rear points to 30.

*front*rear102030NULL

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

*front*rear1020NULL

Queue: 10 → 20. Call dequeue three times.

*front*rear1020NULLold

old = *front.

*front*rear1020NULLold

*x = 10; *front = old->link → node(20).

*front*rear1020NULLold

*front ≠ NULL: rear is unchanged.

*front*rear1020NULL

free(old); main prints 10.

*front*rear1020NULLold

old = *front.

*frontNULL*rear1020NULLold

*x = 20; *front = old->link → NULL.

*frontNULL*rearNULL1020NULLold

*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)!

*frontNULL*rearNULL1020NULL

free(old); main prints 20.

*frontNULL*rearNULL1020NULL

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

CriterionLinear arrayCircular arrayLinked list
enqueue / dequeueO(1), but “false full”O(1)O(1) (malloc/free)
Shifting needed?Yes: O(n)NoNo
CapacityMAXMAX − 1 (or MAX with a count)Up to available memory
Extra memoryNoneNoneOne pointer per item
Special casefront/rear hit the endWrap-around and full/empty testrear = 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)

03152103204push frontpop frontpush backpop back
  • 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

100front201234010120234front = 0 count = 2 last = (front+count−1) % 5 = 1

CAP = 5; push_back has stored 10 and 20. Now push 5 and 3 at the front, then pop the back twice.

100front201234010120234front = 0 count = 2 last = (front+count−1) % 5 = 1

count = 2 < 5, there is room.

100201234front010120234front = 4 count = 2 last = (front+count−1) % 5 = 0

front = (0 − 1 + 5) % 5 = 4: one step back from 0 is the end of the array.

1002012354front0101202345front = 4 count = 3 last = (front+count−1) % 5 = 1

data[4] = 5; count = 3.

1002012354front0101202345front = 4 count = 3 last = (front+count−1) % 5 = 1

count = 3 < 5, there is room.

10020123front540101202345front = 3 count = 3 last = (front+count−1) % 5 = 0

front = (4 − 1 + 5) % 5 = 3.

100201233front5401012023345front = 3 count = 4 last = (front+count−1) % 5 = 1

data[3] = 3; count = 4.

100201233front5401012023345front = 3 count = 4 last = (front+count−1) % 5 = 1

Last position = (3 + 4 − 1) % 5 = 1; *x = 20.

1001233front54010123345front = 3 count = 3 last = (front+count−1) % 5 = 0

count = 3. (front is unchanged.)

1001233front54010123345front = 3 count = 3 last = (front+count−1) % 5 = 0

Last position = (3 + 3 − 1) % 5 = 0; *x = 10.

01233front540123345front = 3 count = 2 last = (front+count−1) % 5 = 4

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

Splitting into segments

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].

Two queues

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.

Circular within a 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)).

Today

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

queue:P0P1P2left: P0=5 P1=2 P2=4timeline:01234567891011

Three processes need P0 = 5, P1 = 2, P2 = 4 units of work. Time slice Q = 2 (round robin).

queue:P1P2left: P0=3 P1=2 P2=4timeline:P001234567891011

P0 is taken from the front and runs 2 units; t = 2.

queue:P1P2P0left: P0=3 P1=2 P2=4timeline:P001234567891011

P0 has 3 units left → goes back to the rear.

queue:P2P0left: P0=3 P1=0 P2=4timeline:P0P101234567891011

P1 is taken from the front and runs 2 units; t = 4.

queue:P2P0left: P0=3 P1=0 P2=4timeline:P0P101234567891011

P1 is finished; it doesn't rejoin the queue.

queue:P0left: P0=3 P1=0 P2=2timeline:P0P1P201234567891011

P2 is taken from the front and runs 2 units; t = 6.

queue:P0P2left: P0=3 P1=0 P2=2timeline:P0P1P201234567891011

P2 has 2 units left → goes back to the rear.

queue:P2left: P0=1 P1=0 P2=2timeline:P0P1P2P001234567891011

P0 is taken from the front and runs 2 units; t = 8.

queue:P2P0left: P0=1 P1=0 P2=2timeline:P0P1P2P001234567891011

P0 has 1 unit left → goes back to the rear.

queue:P0left: P0=1 P1=0 P2=0timeline:P0P1P2P0P201234567891011

P2 is taken from the front and runs 2 units; t = 10.

queue:P0left: P0=1 P1=0 P2=0timeline:P0P1P2P0P201234567891011

P2 is finished; it doesn't rejoin the queue.

queue:left: P0=0 P1=0 P2=0timeline:P0P1P2P0P2P001234567891011

P0 is taken from the front and runs 1 unit; t = 11.

queue:left: P0=0 P1=0 P2=0timeline:P0P1P2P0P2P001234567891011

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

inouttransfer (reverses)

The queue is made of two stacks. Enqueue 1, 2, 3; dequeue; enqueue 4; dequeue three times.

1inouttransfer (reverses)

enqueue(1): push onto the in stack, O(1).

12inouttransfer (reverses)

enqueue(2): push onto the in stack, O(1).

123inouttransfer (reverses)

enqueue(3): push onto the in stack, O(1).

123inouttransfer (reverses)

The out stack is empty → transfer everything from the in stack.

12in3outtransfer (reverses)

Pop 3 from in, push it onto out.

1in32outtransfer (reverses)

Pop 2 from in, push it onto out.

in321outtransfer (reverses)

Pop 1 from in, push it onto out.

in32outtransfer (reverses)

The top of the out stack is 1, the oldest item. FIFO achieved.

4in32outtransfer (reverses)

enqueue(4): push onto the in stack, O(1).

4in3outtransfer (reverses)

The top of the out stack is 2, the oldest item. FIFO achieved.

4inouttransfer (reverses)

The top of the out stack is 3, the oldest item. FIFO achieved.

4inouttransfer (reverses)

The out stack is empty → transfer everything from the in stack.

in4outtransfer (reverses)

Pop 4 from in, push it onto out.

inouttransfer (reverses)

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?

ProblemStructure
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!
Instructor “You know something called a queue, and the word queue appears here too. But in the queue we know, you add at the back and take from the front. This one is different…”

Lab · C code step by step

Lab: Circular Queue

Summary

Complexity Summary

OperationLinear arrayCircular arrayLinkedDeque (circular)
enqueueO(1)*O(1)O(1)O(1) at both ends
dequeueO(1)O(1)O(1)O(1) at both ends
front / empty / fullO(1)O(1)O(1)O(1)
item countrear − front(rear−front+MAX)%MAXO(n) or a countcount
memoryMAXMAXn · (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

1Taking rear == MAX−1 in a linear queue as truly full.
2Forgetting % MAX in a circular queue and writing past the array.
3Advancing rear first and not rolling it back when full: the queue then looks empty.
4Writing (i − 1) % MAX to step back: in C the result can be negative.
5Not setting rear = NULL when the last item leaves a linked queue.
6Forgetting to update front on the first insert into an empty queue.

Summary

Exercises

  1. MAX = 6, front = 4, rear = 1: how many items are there, and at which indices?
  2. Write enqueue and dequeue for a circular queue that uses the flag method.
  3. Build a queue from two stacks. What is the amortized cost of dequeue?
  4. Implement a queue as a circular linked list with only a rear pointer.
  5. Run the round-robin example with Q = 3: when does each process finish?
Hints / answers
  1. (1 − 4 + 6) % 6 = 3 items: indices 5, 0, 1 (from just after front up to rear).
  2. Empty: front == rear && !last_was_enq; full: front == rear && last_was_enq. enqueue sets the flag to 1, dequeue to 0.
  3. 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).
  4. rear->link is the front node. Enqueue: new_node->link = rear->link; rear->link = new_node; rear = new_node. Dequeue: front = rear->link.
  5. 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

FIFO

Insert at the rear, remove at the front; first in, first out.

Linear queue

Simple, but once rear hits the end the free space at the front is lost; shifting is expensive.

Circular queue

Wrap with % MAX; empty: front == rear, full: (rear+1)%MAX == front.

Full vs. empty

Leave one cell empty, or keep a count or a flag.

Linked queue

front and rear pointers; rear = NULL when the last item leaves.

Applications

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.

The End

Chapter 7: Queues
Next chapter: Chapter 8: Stack and Queue Applications · Course page
1 / 1 Data Structures and Algorithms with C