Data Structures & Algorithms / Module 1: Linear data structures

Topic 1.5

Queue and circular queue

A line with two ends: first come, first served, without shuffling anyone forward.

9 min · beginner

Watch: first in, first out. Watch the front and back markers travel round the tray.

01234567447722
Head: the item that leaves nextTail: the pocket that fills nextA tray with 8 pockets numbered 0 to 7. Items enter at the tail and leave at the head, so the first in is the first out. Both arms turn to the next pocket, and after pocket 7 they wrap back to 0. Nothing ever has to be shifted.
leaves in order: 4, 7, 2

    Like the line at a checkout

    New people stand at the very back. The cashier serves the person at the front. No cutting in. A queue in a program works the same way, with two moves:

    1. enqueue: join the line at the back. That spot is called the tail.
    2. dequeue: leave the line from the front. That spot is called the head.

    The rule is called FIFO (first in, first out). It is the opposite of a stack, where the last one in leaves first.

    The hidden problem: shuffling everyone forward

    The easiest queue in JavaScript is push to join and shift to leave. It gives the right answer, but there is a hidden cost. Every time the person at the front leaves, shift moves everyone else one step forward.

    Picture a cashier who makes a hundred people step forward every time one person pays. With a few people you won't notice. With millions of jobs in the queue, all the time goes into shuffling.

    Code, for programmersCorrect, but slow for big queues
    const queue = [];
    queue.push("a");      // join at the back
    queue.push("b");
    queue.shift();        // "a" leaves, and "b" is moved to the front

    The fix: a queue that goes round in a circle

    The figure above never moves an item. Items stay in their pockets; only two pointers move. The head arm steps forward every time something leaves, and the tail arm steps forward every time something joins. After the last pocket, both wrap back to pocket 0, like the hand of a clock.

    This is a circular queue. Joining and leaving are both fast, however long the line is.

    Code, for programmersA circular queue: only head and size move
    class CircularQueue {
      constructor(capacity) {
        this.slots = new Array(capacity);
        this.head = 0;   // where the next item leaves
        this.size = 0;   // how many are waiting
      }
      enqueue(x) {
        if (this.size === this.slots.length) throw new Error("full");
        const tail = (this.head + this.size) % this.slots.length;   // % wraps back to 0
        this.slots[tail] = x;
        this.size++;
      }
      dequeue() {
        if (this.size === 0) return undefined;
        const x = this.slots[this.head];
        this.slots[this.head] = undefined;
        this.head = (this.head + 1) % this.slots.length;
        this.size--;
        return x;
      }
    }

    Where queues are used

    • Background work, like sending emails or building reports: everything is done in the order it arrived.
    • Browsers queue up things to do (clicks, timers, replies from the server) and handle them one at a time.
    • Spreading visitors across servers in turn, like the arm going round the tray.
    • Video and music streaming holds chunks of data in a circular queue so playback doesn't stutter.

    Quiz

    1. An empty queue gets enqueue(1), enqueue(2), enqueue(3), then dequeue(). What comes out?

    2. Why is array.shift() slow for a big queue?

    3. A circular queue has 8 pockets (0 to 7). Head is at pocket 6 and 3 items are waiting. Which pocket does the next item go into?

    4. Which is the best fit for a queue?

    0 of 4 answered.