Kodewick
Start learning →
Queues, circular queues and deque16 / 52

Queues, circular queues and deque

Lesson 16 of 52 · Part 3 · Stacks and queues · about 16 minutes

A queue adds at the rear and removes at the front (FIFO); a circular queue wraps around to avoid false overflow, empty when front == rear and full when (rear + 1) % MAX == front, and the STL has std::queue and std::deque.

Print jobs, message queues, the nodes waiting to be visited in a breadth-first search: all are handled first come, first served (FIFO, first in first out). A structure used that way is a queue: in at the rear, out at the front. This lesson writes a circular queue and a linked queue by hand, then looks at the STL's std::queue and std::deque.

Array queues and "false overflow"

In an array, front points at the front element and rear points at the slot after the last element (where the next one goes). Enqueue stores at data[rear] and does rear++; dequeue takes data[front] and does front++.

data (MAX = 6)012345↑front↑rear

An array queue: front and rear only move right. Slots freed at the front by dequeues are never used again
Choose one

An array queue with MAX = 5 (rear points at the next delete slot): enqueue a, b, c, d, then dequeue twice. What are front and rear now?

Choose one

What does "false overflow" mean?

Circular queues: wrap round to 0

The fix is to join the array's ends into a ring: after the last slot, rear goes back to 0. That's written with modulo:

1rear = (rear + 1) % MAX;     // after 5 comes (5 + 1) % 6 = 02front = (front + 1) % MAX;
A circular queue drawn as a ring: MAX = 6, index 0 at the top, going clockwise. 40, 50, 60 are in slots 4, 5, 0 (they've wrapped round); front points at 4, rear at the next free slot, 1. On the right, top to bottom: the length formula with the numbers put in, the empty test, the full test

Wrapping brings a new problem: when the queue is empty, front == rear; when it's full, rear has gone all the way round and caught up with front, so front == rear too, and you can't tell them apart. The usual fix is to leave one slot unused: if one more step of rear would hit front, the queue counts as full.

ConditionWhy
Emptyfront == rearNo elements at all
Full(rear + 1) % MAX == frontOne slot kept free, so full and empty look different
Length(rear - front + MAX) % MAXAfter wrapping, rear can be less than front; adding MAX before the modulo keeps it from going negative

So a circular queue with MAX = 6 holds at most 5.

data304050012345↑front↑rear

A circular queue, MAX = 6: after 5, rear wraps to 0, and the slots freed at the front are usable again

Put the array and the two indexes in a class:

main.cpp
1#include <iostream>2using namespace std;3 4const int MAX = 6;5 6class CircularQueue {7    int data[MAX];8public:9    int front = 0, rear = 0;             // public only so main can print them10 11    bool enqueue(int x) {12        if ((rear + 1) % MAX == front) return false;   // full13        data[rear] = x;14        rear = (rear + 1) % MAX;15        return true;16    }17    void dequeue() { front = (front + 1) % MAX; }      // check empty() before calling18    int peek() const { return data[front]; }19    bool empty() const { return front == rear; }20    int size() const { return (rear - front + MAX) % MAX; }21};22 23int main() {24    CircularQueue q;25    for (int i = 1; i <= 6; i++)26        if (!q.enqueue(i * 10))27            cout << i * 10 << " doesn't fit: full (length " << q.size() << ")\n";28    q.dequeue();29    q.dequeue();30    q.enqueue(60);31    q.enqueue(70);32    cout << "front = " << q.front << ", rear = " << q.rear << ", length " << q.size() << "\n";33    while (!q.empty()) {34        cout << q.peek() << " ";35        q.dequeue();36    }37    cout << "\n";38    return 0;39}
Output
60 doesn't fit: full (length 5)
front = 2, rear = 1, length 5
30 40 50 60 70 
Guess the outputA wrong guess is fine

A circular queue with MAX = 8 has front = 6 and rear = 2. How many elements are in it?

1#include <iostream>2using namespace std;3 4const int MAX = 8;5 6int main() {7    int front = 6, rear = 2;8    cout << (rear - front + MAX) % MAX << "\n";9    return 0;10}

In exams: Sometimes rear points at the last element itself; then the length is (rear - front + 1 + MAX) % MAX and full is (rear + 2) % MAX == front. And "a circular queue in an array A[0..n]" means n + 1 slots, so MAX = n + 1.

Choose one

A circular queue with MAX = 8 (rear points at the next delete slot) has front = 3 and rear = 2. What state is it in?

Fill inTap one to fill a blank; tap a blank to take it back

MAX = 4, and 1 to 5 are enqueued into an empty queue. Fill in the "full" check so the program prints how many went in: 3.

1#include <iostream>2using namespace std;3 4const int MAX = 4;5int q[MAX];6int front = 0, rear = 0;7 8bool enqueue(int x) {9    if ( == front) return false;10    q[rear] = x;11    rear = (rear + 1) % MAX;12    return true;13}14 15int main() {16    int ok = 0;17    for (int i = 1; i <= 5; i++)18        ok += enqueue(i);19    cout << ok << "\n";20    return 0;21}
Exercise 1

Write a circular queue

Fill in the four functions of CircularQueue: enqueue returns false when full; rear and front wrap round with modulo as they move on.

It should print
3
2 3 5
exercise1.cpp
1#include <iostream>2using namespace std;3 4const int MAX = 4;5 6class CircularQueue {7    int data[MAX];8    int front = 0, rear = 0;9public:10    bool enqueue(int x) {11        // full: (rear + 1) % MAX == front12        return true;13    }14    void dequeue() {15        // front moves on one slot16    }17    int peek() const { return 0; }        // make it the front18    bool empty() const { return true; }   // make it front == rear19};20 21int main() {22    CircularQueue q;23    int ok = 0;24    for (int i = 1; i <= 4; i++)25        ok += q.enqueue(i);26    q.dequeue();27    q.enqueue(5);28    cout << ok << "\n";29    while (!q.empty()) {30        cout << q.peek() << " ";31        q.dequeue();32    }33    cout << "\n";34    return 0;35}
Output
Press Run or Ctrl+Enter
Exercise 2

Work out the length

Fill in len so it's right for all three pairs of front and rear in main (MAX = 10).

It should print
5 5 0
exercise2.cpp
1#include <iostream>2using namespace std;3 4const int MAX = 10;5 6int len(int front, int rear) {7    return 0;   // make it the length formula8}9 10int main() {11    cout << len(2, 7) << " " << len(7, 2) << " " << len(4, 4) << "\n";12    return 0;13}
Output
Press Run or Ctrl+Enter

Linked queues

A linked list never has false overflow: front points at the first node and rear at the last. Enqueue links a node after rear (inserting at the tail), dequeue removes front.

front↓rear↓
10a
20b
30c
nullptr

A linked queue: enqueue hooks on after rear, dequeue takes front; after the last one goes, rear must go back to nullptr too
main.cpp
1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10class LinkedQueue {11    Node* front = nullptr;               // the first node: leave from here12    Node* rear = nullptr;                // the last node: link after it13public:14    void enqueue(int x) {15        Node* n = new Node(x);16        if (rear == nullptr) front = rear = n;   // it was empty17        else { rear->next = n; rear = n; }18    }19    void dequeue() {20        Node* old = front;21        front = front->next;22        if (front == nullptr) rear = nullptr;    // now empty: clear rear too23        delete old;24    }25    int peek() const { return front->val; }26    bool empty() const { return front == nullptr; }27    ~LinkedQueue() {28        while (!empty()) dequeue();29    }30};31 32int main() {33    LinkedQueue q;34    q.enqueue(1);35    q.enqueue(2);36    q.dequeue();37    q.dequeue();                         // empty: rear is back to nullptr too38    q.enqueue(3);39    q.enqueue(4);40    while (!q.empty()) {41        cout << q.peek() << " ";42        q.dequeue();43    }44    cout << "\n";45    return 0;46}
Output
3 4 

The line most easily forgotten is if (front == nullptr) rear = nullptr; in dequeue: dequeue the only node and front becomes nullptr, but rear still points at the node just deleted. The next enqueue sees a rear that isn't null and writes rear->next: into memory that has already been given back.

Choose one

A linked queue has one node left and you dequeue it. What happens if if (front == nullptr) rear = nullptr; is missing?

Guess the outputA wrong guess is fine

This linked queue enqueues and dequeues a few times. What does it print at the end?

1#include <iostream>2using namespace std;3 4struct Node {5    int val;6    Node* next;7    Node(int v) : val(v), next(nullptr) {}8};9 10Node* front = nullptr;11Node* rear = nullptr;12 13void enqueue(int x) {14    Node* n = new Node(x);15    if (rear == nullptr) front = rear = n;16    else { rear->next = n; rear = n; }17}18 19int dequeue() {20    Node* old = front;21    int x = old->val;22    front = front->next;23    if (front == nullptr) rear = nullptr;24    delete old;25    return x;26}27 28int main() {29    enqueue(1);30    enqueue(2);31    cout << dequeue() << " ";32    enqueue(3);33    cout << dequeue() << " ";34    cout << dequeue() << " ";35    enqueue(4);36    cout << front->val << "\n";37    return 0;38}

With the STL

The STL has two ready-made ones: std::queue (<queue>), in at the back and out at the front only; and std::deque (<deque>, double-ended queue), in and out at both ends, with indexing too.

main.cpp
1#include <iostream>2#include <queue>3#include <deque>4using namespace std;5 6int main() {7    queue<int> q;                 // by default there's a deque<int> inside8    for (int i = 1; i <= 4; i++)9        q.push(i * 10);10    cout << "front " << q.front() << ", back " << q.back() << ", size " << q.size() << "\n";11    q.pop();                      // removes the 10 at the front, returns nothing12    cout << "after pop, front " << q.front() << "\n";13 14    deque<int> d = {3, 4};15    d.push_front(2);16    d.push_front(1);17    d.push_back(5);18    d.pop_back();19    for (int i = 0; i < (int)d.size(); i++)20        cout << d[i] << " ";21    cout << "\n";22    return 0;23}
Output
front 10, back 40, size 4
after pop, front 20
1 2 3 4 

Like last lesson's std::stack, std::queue is a container adaptor: it holds a deque inside, push is push_back, pop is pop_front, and front / back look at the two ends. It can't sit on a vector, because vector has no pop_front: removing the first element moves all the others forward, O(n).

A deque isn't one contiguous array inside but many small fixed-size blocks, with a small array of pointers keeping them in order. When the front is full a block is added in front; when the back is full, one is added behind; existing elements never move. Indexing first works out which block and where in it, so it's O(1) too, just one step more than a vector.

OperationqueuedequeCost
In at the backpush(x)push_back(x)O(1)
Out at the frontpop()pop_front()O(1)
In at the front / out at the backNonepush_front(x) / pop_back()O(1)
Look at the endsfront() / back()front() / back()O(1)
By indexNoned[i]O(1)
Insert / erase in the middleNoneinsert / eraseO(n)

As with the stack, front() or pop() on an empty queue is undefined behaviour; ask empty() first.

In interviews: BFS (visiting a tree or a graph level by level) uses queue<int>; "sliding window maximum" keeps indexes in a deque<int>, going in and out at both ends; "design a circular queue" means writing the class above, and it tests the modulo and the spare slot. Asked how deque differs from vector: deque is O(1) at both ends and not stored in one piece; vector is O(1) only at the back and is one contiguous block.

Guess the outputA wrong guess is fine

This deque takes items in and out at both ends. What does it print, front to back?

1#include <iostream>2#include <deque>3using namespace std;4 5int main() {6    deque<int> d;7    d.push_back(1);8    d.push_back(2);9    d.push_front(3);10    d.pop_back();11    d.push_front(4);12    for (int x : d)13        cout << x << " ";14    cout << "\n";15    return 0;16}
Choose one

Why can’t you use queue<int, vector<int>> (a queue on top of a vector)?

Summary

Take-away

Queues: wrap with modulo, keep one slot free; in the STL, queue and deque

  • In at the rear, out at the front; rear points at the next free slot
  • One step: i = (i + 1) % MAX; empty is front == rear, full is (rear + 1) % MAX == front
  • Length (rear - front + MAX) % MAX; it holds at most MAX − 1
  • When a linked queue's dequeue empties it, set rear to nullptr too
  • queue is a layer over a deque; a deque is small blocks, O(1) in and out at both ends
1data[rear] = x;2rear = (rear + 1) % MAX;3queue<int> q;4q.push(x);5int y = q.front();6q.pop();