3.2.4 · D3Linear Data Structures

Worked examples — Circular linked list — applications

3,897 words18 min readBack to topic

Before we start, two words we'll reuse:


The scenario matrix

Every problem this topic can throw lives in one of these cells. The examples below are labelled with the cell they cover.

Cell Case class What makes it tricky
A Empty list (0 nodes) No head, no tail — the degenerate base case
B Single node (1 node) The node must point to itself; head = tail
C Insert front / insert back Must re-close the loop (tail.next = head)
D Delete a middle node Relink prev.next = victim.next, keep loop
E Delete the head or the tail The "first"/"last" label moves — special care
F Traversal (count / print) Stop at p == start, not at null; empty needs a pre-check
G Wrap-around counting (Josephus) Counting crosses the seam back to the start
H Buffer overflow (ring buffer full) Oldest data is overwritten when write meets read
I Real-world word problem Round-robin scheduling over several rounds
J Exam twist / limiting value k larger than n; k = 1; huge k modulo n

Prerequisites you may want open: Singly Linked List, Doubly Linked List, Queue.


Worked examples

Example 1 — The empty list (Cell A)


Example 2 — Single node stays a loop (Cell B)


Example 3 — Insert front and back, keep the loop (Cell C)


Example 4 — Delete a middle node (Cell D)


Example 5 — Delete the head (Cell E)


Example 6 — Delete the tail (Cell E)


Example 7 — Traversal that must not run forever (Cell F)


Example 8 — Josephus with wrap-around counting (Cell G)


Example 9 — Ring buffer overflow (Cell H)


Example 10 — Round-robin real-world (Cell I)


Example 11 — Exam twists: k = 1, k > n (Cell J)


Recall Quick self-test across all cells

Empty-list insert makes the node point to ::: itself, and sets head = tail = node. Correct traversal stop condition ::: p == start with a do-while (never p == null). Traversal must first guard against ::: head == null (return 0) before the loop, else it dereferences null. Deleting the head requires also setting ::: tail.next = new head to re-close the loop. Deleting the tail requires also setting ::: tail = prev (move the tail label back one node). Josephus n=7, k=3 survivor ::: person 4. Ring buffer size 4, write a,b,c,d,e then read → returns ::: b (a was overwritten). Round-robin quantum 3 on P5 Q2 R4 finish order ::: Q, P, R. Josephus n=5, k=1 survivor ::: person 5.