Lesson 15 · Linear structures

Queues

A queue is a First-In-First-Out (FIFO) structure: items join at the rear and leave from the front, so the one that has waited longest goes first. Both ends must work in O(1), and the obvious array version gets that wrong.

Queues concept diagramA visual explanation of the layout and operations shown in this lesson.elements leave from the front and arrive at the backABCDfrontbackdequeueenqueuefirst in, first out
1

FIFO and the Two Ends

A queue is a linear structure with a strict access rule: items are added at one end, the rear, and removed from the other, the front. The item that has waited longest leaves next: First In, First Out (FIFO), like a line at a ticket counter.

Like a stack, a queue is defined by what it does not allow: no access to the middle, no indexing, no search. That narrow interface is a promise about order.

There are four operations. enqueue adds an item at the rear. dequeue removes and returns the item at the front. peek (or front) reads the front without removing it. isEmpty reports whether anything is left. A dequeue on an empty queue is an underflow and must throw or return a clear signal, never garbage.

Enqueue and dequeue are both expected to be O(1). A queue with an O(n) dequeue defeats the reason for using one, and the next section shows that the obvious array version has exactly that problem.

  • Stack vs queue: a stack removes from the end it adds to; a queue removes from the other end
  • A bounded queue can also overflow: enqueue on a full fixed-size queue must block, reject or overwrite
  • Peek on an empty queue is an underflow too, not only dequeue
2

Why a Plain Array Fails

Take a plain array with a rear index. Enqueue writes at rear and adds 1: O(1). Dequeue returns item 0 and then has to move every remaining item one slot left so the front is at index 0 again. That shift is O(n), and it happens on every removal.

So draining a queue of n items costs O(n²). Python's list.pop(0) does exactly this, which is why collections.deque exists and why a list used as a queue is a common performance bug.

The obvious repair is to stop shifting: keep a front index as well and dequeue by adding 1 to it. Both operations are O(1) now, but the slots before front are never used again. This linear queue eventually has rear at the end of the array and reports itself full while holding almost nothing.

The real fix is to let the indices wrap around: rear = (rear + 1) % capacity. The array becomes a ring and the freed slots are reused. That is a circular queue, and nearly every fixed-size queue is built that way.

A queue built from linked list nodes avoids the problem entirely. Keep head at the front and tail at the rear: enqueue links the new node after tail and moves tail; dequeue moves head to the next node. Both are O(1), nothing shifts, and there is no fixed capacity. The cost is a pointer per item and memory spread around the heap. When the last item leaves, tail must be set to null as well; the tracer below shows why.

Two stacks also make a queue. Enqueue pushes onto an in stack. Dequeue pops from an out stack, and only when out is empty does it move everything from in across, which reverses the order. Each item is moved at most once, so dequeue is amortised O(1), even though one dequeue can cost O(n). Practice it in implement queue using stacks.

Five ways to back a queue
BackingEnqueueDequeueProblem
Array, shift on dequeueO(1)O(n)Shifting dominates everything
Array, moving front indexO(1)O(1)Leaks the space it passes over
Circular arrayO(1)O(1)Fixed capacity; full and empty look alike
Linked list with head and tailO(1)O(1)Pointer overhead, poor locality
Two stacksO(1)O(1) amortisedOne dequeue can cost O(n)
  • Never use list.pop(0) as a dequeue in Python; collections.deque.popleft() is O(1)
  • A linked queue must reset tail when it becomes empty, or the next enqueue is lost
  • Practice: implement queue using arrays
3

The Types of Queue

Data structure courses teach four types of queue, and questions usually name one. Each keeps part of the FIFO rule and relaxes another.

A simple queue, also called a linear queue, is the base case: enqueue at the rear, dequeue at the front, strict arrival order.

A circular queue has the same interface with wrapped indices, so a fixed array is fully reused. Its one subtlety is that front == rear can mean empty or full; a count or one unused slot tells them apart. See circular queues.

A priority queue breaks FIFO on purpose: each item carries a priority and the most urgent one is served next, whenever it arrived. Finding that item quickly needs a heap, which gives O(log n) insert and remove instead of O(1). It is a queue by interface, not by order. See priority queues.

A deque (double-ended queue) relaxes the other way and allows adding and removing at both ends. Used rear-in, front-out it is a queue; used rear-in, rear-out it is a stack. See deques.

  • Python: collections.deque (append, popleft); queue.Queue adds locking for threads
  • Java: ArrayDeque with offer and poll; LinkedList also implements Queue
  • C++: std::queue, an adapter over std::deque by default
Key reference

Terms, operations, and practical uses

Core operations

  • EnqueueAdding an item at the rear (tail) of the queue. O(1).
  • DequeueRemoving and returning the item at the front (head) of the queue. O(1).
  • FIFOFirst In, First Out: the item that has waited longest leaves first.

Implementation problems

  • Array ShiftingThe flaw of a naive array queue: every dequeue moves the remaining items one slot left, O(n).
  • Two-Stack QueueEnqueue pushes onto one stack; dequeue pops from a second, refilling it from the first only when empty. Amortised O(1).
  • Linked List QueueHead and tail pointers give O(1) enqueue and dequeue with no capacity limit.

Practical applications

  • Breadth-First Search (BFS)A queue explores a graph level by level, which gives shortest paths in unweighted graphs.
  • Task SchedulingBuffering requests so worker threads handle them in the order they arrived.
  • Message BrokersSystems such as Kafka and RabbitMQ hold messages durably so services can consume them in order.
Implementation

Code in Python, C++ and Java

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None


class Queue:
    def __init__(self):
        self.head = self.tail = None
    def enqueue(self, val):
        new_node = Node(val)
        if not self.tail:
            self.head = self.tail = new_node
            return
        self.tail.next = new_node
        self.tail = new_node
    def dequeue(self):
        if not self.head:
            return None
        val = self.head.val
        self.head = self.head.next
        if not self.head:
            self.tail = None
        return val


q = Queue()
q.enqueue(10)
q.enqueue(20)
q.dequeue()
q.enqueue(30)
print('Front is ' + str(q.head.val) + ', Rear is ' + str(q.tail.val))
#include <iostream>
using namespace std;

struct Node { int val; Node* next; Node(int x): val(x), next(NULL) {}; };
class Queue {
public:
    Node *head = NULL, *tail = NULL;
    void enqueue(int val) {
        Node* newNode = new Node(val);
        if (!tail) {
            head = tail = newNode;
            return;
        }
        tail->next = newNode;
        tail = newNode;
    }
    int dequeue() {
        if (!head) return -1;
        int v = head->val;
        Node* temp = head;
        head = head->next;
        if (!head) tail = NULL;
        delete temp;
        return v;
    }
};

int main() {
    Queue q;
    q.enqueue(10);
    q.enqueue(20);
    q.dequeue();
    q.enqueue(30);
    cout << "Front is " << q.head->val << ", Rear is " << q.tail->val << '\n';
}
class Main {
    static class Node { int val; Node next; Node(int x) { val = x; } }
    static class Queue {
        Node head, tail;
        void enqueue(int val) {
            Node newNode = new Node(val);
            if (tail == null) {
                head = tail = newNode;
                return;
            }
            tail.next = newNode;
            tail = newNode;
        }
        int dequeue() {
            if (head == null) return -1;
            int v = head.val;
            head = head.next;
            if (head == null) tail = null;
            return v;
        }
    }

    public static void main(String[] args) {
        Queue q = new Queue();
        q.enqueue(10);
        q.enqueue(20);
        q.dequeue();
        q.enqueue(30);
        System.out.println("Front is " + q.head.val + ", Rear is " + q.tail.val);
    }
}
Watch it run

Step through it

Running on enqueue 10, enqueue 20, dequeue, enqueue 30; then dequeue twice and enqueue 40

starthead = nulltail = nullqueue, front to back: emptyhead = tail = null
Step 1

An empty queue

A linked-list queue keeps two pointers: head, where items leave, and tail, where they arrive. With nothing in the queue, both are null.

Output
1 / 12
4

Breadth-First Search Depends on FIFO

The most important use is breadth-first search, and BFS does not just happen to use a queue. Mark the start node as seen and enqueue it. Then repeatedly dequeue a node and enqueue each neighbour not yet seen, marking it as it goes in, so no node enters the queue twice.

Because the queue is FIFO, every node at distance d is dequeued before any node at distance d + 1. The queue never holds nodes from more than two neighbouring levels, and the search spreads outward one ring at a time.

That makes BFS a shortest-path algorithm on unweighted graphs: when a node is first reached, no shorter route to it exists, because a shorter one would have put it in an earlier ring. The proof rests on FIFO alone. Swap the queue for a stack and the same loop becomes depth-first search and loses the guarantee.

Level-order tree traversal is BFS on a tree. Reading the queue's size at the start of each round tells you how many nodes are on the current level, which gives per-level output without storing depths.

  • Marking a node when it is dequeued, not when it is enqueued, lets it enter the queue once per incoming edge
  • Operating systems keep ready queues and print queues in FIFO order
  • Practice: BFS of graph, binary tree level order traversal