Lesson 11 · Linear structures

Circular Linked Lists

A circular linked list closes the loop: the last node points back to the first instead of to null. That one change removes the natural stopping point, so traversal needs an explicit guard — and buys O(1) access to both ends from a single pointer.

Circular Linked Lists concept diagramA visual explanation of the layout and operations shown in this lesson.the last node links back to the first, so there is no nullABCDD.next is A, so traversal stops when it returns to the start
1

Closing the Loop

A circular linked list replaces the null at the end with a link from the last node back to the first. Every node then has a real successor, and following next goes round the list forever instead of stopping. It is one of the types of linked list, next to singly and doubly linked lists.

Both variants exist. A circular singly linked list gives each node one next pointer, with the tail's pointing at the head. A circular doubly linked list adds prev, so the head's prev points at the tail as well and the loop closes in both directions.

The structural consequence is that no node is first or last by nature. Any node can be the entry point, and 'head' is just the node you choose to hold a reference to. That symmetry is what makes rotation free, where a linear list would have to relink or move data.

The cost is that every loop needs a different termination condition. while (current != null) never terminates here. The correct form is a do-while that saves the starting node and stops on returning to it: process the current node, advance, and continue while current != start.

Writing it as a plain while (current != start) fails on the first iteration, since the condition is immediately false — the loop body never runs. This is the standard circular-list bug, and it is why the do-while form is the one to remember.

The empty list needs care too. It cannot be represented by 'head is null and the last node points nowhere', because there is no last node. The usual convention is that an empty circular list has a null head, and a single-node list has a node whose next points at itself — a case worth testing explicitly, since it is easy to write insertion code that leaves the sole node pointing at null instead.

  • Empty list: tail (or head) is null; there are no nodes and no links
  • Comparing nodes by identity (is, == on references) matters: two nodes can hold the same value
  • A loop that must stop early (search) still needs the start check, or a missing value loops forever
2

Why Keep the Tail Instead of the Head

A useful implementation choice is to store a reference to the tail rather than the head. It seems arbitrary and is not.

Given the tail, the head is immediately available as tail.next — one dereference, no traversal. So holding the tail gives O(1) access to both ends, where holding the head gives O(1) access to only the head and requires a full O(n) walk to reach the tail.

That makes both insertions cheap. Inserting at the front: create the node, set its next to tail.next (the old head), and point tail.next at it. Inserting at the back: do exactly the same, then additionally reassign tail to the new node. The two operations differ by a single line, which is a neat illustration of how little separates the ends in a circular structure.

That is exactly what a queue needs, enqueue at one end and dequeue at the other, both O(1), with one pointer where a linear singly linked list needs two.

Rotation is where the structure shines. Rotating a linear list by k positions means finding a new end and relinking. In a circular list, rotating by one is tail = tail.next: one assignment, O(1), with no node relinked and no value copied. Rotating by k is k such steps, and k mod n is enough.

Deletion carries the usual singly linked caveat: removing a node requires its predecessor, so it costs O(n) to find unless the list is doubly linked. Deleting the head is O(1) given the tail, since tail.next is the head and tail is its predecessor by definition.

3

Round-Robin and Ring Buffers

The structure's applications all share one shape: a fixed set of items cycled through repeatedly, with no natural end to the sequence.

Round-robin turn-taking is the canonical case. A round-robin scheduler gives each runnable process a time slice, then moves to the next, and after the last it returns to the first. A circular list expresses this directly: hold one pointer and advance it, with no bounds check and no wrap-around branch, because the wrap is the structure. The Linux kernel's list_head, used throughout the kernel including the real-time scheduler's per-priority run queues, is a circular doubly linked list.

Ring buffers apply the same idea to data: a fixed-size buffer where writing past the end continues at the beginning. Audio streams, keyboard input and network packet queues all use one. In practice a ring buffer is usually an array with modulo arithmetic rather than linked nodes, covered in circular queues: the indices wrap just as the pointers would, with better cache behaviour and no allocation.

That is worth noting honestly: a circular array is the more common implementation of circular behaviour. The linked version wins only when the number of elements changes frequently, since an array's capacity is fixed.

Other uses fit the same pattern: turn order in a multiplayer game, a slideshow that returns to the first image. The Josephus problem is the classic exercise: n people stand in a circle and every k-th one is removed until one remains. Simulating it on a circular list takes O(n·k). For n = 5 and k = 2 the removals are 2, 4, 1, 5 and person 3 survives. The recurrence J(n) = (J(n − 1) + k) mod n, with J(1) = 0, gives the same answer (index 2, person 3) in O(n) without any list.

  • A circular doubly linked list closes both directions: head.prev is the tail
  • Python's collections.deque is a linked list of blocks, not a circular node list, but rotate(k) gives the same effect
  • A circular array is usually the better choice when the size is fixed
Key reference

Terms, operations, and practical uses

Topology

  • Ring StructureA linked list that forms a closed loop, where the final node connects back to the first node.
  • No Null PointersA properly formed circular list never contains a null reference; traversal can continue infinitely.
  • Tail TrackingKeeping a reference to the tail instead of the head, because tail.next provides instant access to the head.

Traversal mechanics

  • Starting ReferenceTo visit every node once, save the start node, then move and stop when cur returns to it (a do-while, so the start node itself is visited).
  • Infinite LoopsA common bug if a stopping condition is not correctly implemented when searching for an element.
  • Round-RobinContinuously cycling through nodes, giving each a 'turn' before moving to the next.

Applications

  • CPU SchedulingGiving multiple processes a tiny slice of CPU time in a repeating circle to simulate multitasking.
  • Josephus ProblemA mathematical puzzle where every k-th person in a circle is eliminated until one survives.
  • Multiplayer TurnsManaging player turns in a board game, looping back to Player 1 after the last player finishes.
Implementation

Code in Python, C++ and Java

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

# Setup the ring A -> B -> C -> D -> A
a = Node("A")
b = Node("B")
c = Node("C")
d = Node("D")
a.next = b
b.next = c
c.next = d
d.next = a   # the tail closes the ring

start = a
current = a
while True:
    print(current.val)
    current = current.next
    if current == start:
        break
#include <iostream>
#include <string>
using namespace std;

struct Node {
    string val;
    Node* next;
    Node(string x) : val(x), next(NULL) {}
};

int main() {
    Node* a = new Node("A");
    Node* b = new Node("B");
    Node* c = new Node("C");
    Node* d = new Node("D");
    a->next = b;
    b->next = c;
    c->next = d;
    d->next = a;   // the tail closes the ring

    Node* start = a;
    Node* current = a;
    do {
        cout << current->val << '\n';
        current = current->next;
    } while (current != start);
}
class Main {
    static class Node {
        String val;
        Node next;
        Node(String x) { val = x; }
    }
    public static void main(String[] args) {
        Node a = new Node("A");
        Node b = new Node("B");
        Node c = new Node("C");
        Node d = new Node("D");
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = a;   // the tail closes the ring

        Node start = a;
        Node current = a;
        do {
            System.out.println(current.val);
            current = current.next;
        } while (current != start);
    }
}
Watch it run

Step through it

Running on ring A → B → C → D → A, then insert E at the back, Z at the front, rotate, delete the head

ring A → B → C → D → AABCDtailhead = tail.nextD.next = Aevery node has a successorthe link D → A closes the loop
Step 1

Four nodes, and no null anywhere

A, B, C and D each point to the next, and D points back to A instead of to null. The list is held by one pointer, tail, at D. The head needs no pointer of its own: it is always tail.next.

Output
1 / 13
4

When the Cycle Is a Bug

Circularity is sometimes deliberate and sometimes a defect. A linear list that has accidentally acquired a cycle — through a mistaken pointer assignment during insertion or reversal — will hang any traversal written to stop at null.

Floyd's cycle detection (tortoise and hare) finds it in O(n) time and O(1) space. Move slow one node per step and fast two. If fast reaches null, there is no cycle. If there is one, fast enters it and then gains on slow by exactly one node per step, so the gap shrinks to zero and they must meet. The full method is in cycle detection.

That closing-by-one argument is what makes the algorithm a proof rather than a heuristic, and it is the part an exam answer needs — 'they meet eventually' without the reason is an incomplete answer.

To find where the cycle begins, reset one pointer to the head after they meet and move both one step at a time; they next meet at the entry node. The distance from the head to the entry equals the distance from the meeting point to the entry, plus some whole number of laps.

To measure the cycle's length, keep one pointer fixed at the meeting point and walk the other around until it returns, counting the steps.

The alternative is a hash set of visited nodes, which detects a repeat immediately and is simpler to write, but costs O(n) space. Floyd's is preferred when memory is constrained, and it is the expected answer in interviews for exactly that reason.

For a genuinely circular list, note that these detection algorithms report a cycle by design — so code that must handle both kinds needs to know which it is dealing with rather than inferring it.

  • On a deliberately circular list, Floyd's algorithm reports a cycle by design
  • The hash-set check costs O(n) memory but also finds the entry node directly
  • Practice: linked list cycle, linked list cycle II