Circular linked list
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A circular linked list is a chain whose last item points back to the first, forming a ring. Nothing is last, so you can keep going round forever. That fits anything that repeats in turns.
Practical use cases
- Web app: Rotating banner carousel on a home page. A shop home page rotates five promotional banners. After the fifth, it must show the first again. With a ring, the code just follows the next link and never checks "am I at the end?", so adding or removing a banner is a matter of changing one link.
- Web app: Fair assignment of support tickets. A helpdesk has four agents and wants each new ticket to go to the next agent in turn. Keep agents in a ring with a pointer to whose turn it is, and move it one step after each ticket. When an agent goes on leave, remove them from the ring and the rotation continues.
- System: Scheduling and turn-based games. Operating systems give each running program a short slice of processor time in round-robin order. Board games and quiz apps with turns for each player use the same ring, going round and round until the game ends, and a player who leaves is simply unlinked.
The story: Pass the Parcel Forever
At Mira's birthday party the kids played pass-the-parcel. Music on, parcel moves around the circle; music stops, whoever holds it unwraps one layer. Kabir, the party computer-genius, tried to write the game: "Every kid is a node, and each kid points to the kid on the left."
It worked until the parcel reached the last kid in his list. Her pointer said null, and the program crashed: "Nobody to pass to!" Mira laughed. "In a real circle the last kid passes it to the first kid again. A circle never ends."
Kabir made one tiny change: the last node's next points back at the head instead of null. Suddenly the parcel could circle all night and the code never needed an "if we reached the end" check. Turn-taking in games, rotating shifts, round-robin schedulers: all of them are circles.
That is a circular linked list. There is only one new danger: a loop that waits for null will never finish. To visit each node once you start at the head and stop when you arrive back at it. A neat trick is to keep only a pointer to the tail: then the head is simply tail.next, and you can add at both ends in O(1).
How to spot this problem, and where you need it
Something must repeat in a fixed order and wrap around from the last to the first, and your code is full of "if at the end, go back to the start" checks that are easy to get wrong.
Signs you need it
- Words like "round robin", "take turns", "rotate", "wrap around", "repeat all" or "loop back" appear in the requirement.
- You use a modulo or an if-statement every time you step, to reset the position after the final item.
- Members of the cycle join and leave at any time, and re-indexing an array each time is annoying.
Where to use it in a project
- Round-robin task or ticket assignment across workers or agents.
- Carousels, slideshows and repeat-all playlists that must start again after the last item.
- Turn order in multiplayer games, quiz apps and online classroom tools where everyone speaks in turn.
The solution
Link the items in a ring so the last item points back to the first. Keep one pointer to the current item. To advance, move the pointer to the next link; to remove a participant, relink the one before it to the one after. There is no end to test for, so the loop just continues until you stop it.
Payoff: Before: index arithmetic and edge-case bugs with every join or leave. After: one simple step to advance and one relink to change members.
Explain it like I am 8
Think of kids sitting in a circle. Everyone points at the kid on their left. If you keep following the pointers you walk round and round and arrive back where you started. Nobody is "last".
How it works, step by step
- Build nodes like a singly linked list, but the last node's
nextpoints back to the first node. - Keeping a pointer to the tail is handy:
tail.nextis the head. - Insert at the end: new.next = tail.next, tail.next = new, then tail = new. For the very first node, it points to itself.
- Walk one lap: start at the head and use a
do ... whilethat stops when you are back at the head. - Never write
while (cur.next != null)here: it would run forever.
The code in four languages
PHP
<?php
class Node {
public $val;
public ?Node $next = null;
public function __construct($val) { $this->val = $val; }
}
class CircularList {
public ?Node $tail = null; // we keep the tail; the head is tail->next
public function append($val): void {
$node = new Node($val);
if ($this->tail === null) {
$node->next = $node; // a single node points to itself
} else {
$node->next = $this->tail->next; // new node points at the head
$this->tail->next = $node;
}
$this->tail = $node;
}
public function oneLap(): array { // visit every node exactly once
if ($this->tail === null) return [];
$out = [];
$head = $this->tail->next;
$cur = $head;
do {
$out[] = $cur->val;
$cur = $cur->next;
} while ($cur !== $head); // stop when we are back at the start
return $out;
}
public function passParcel(int $passes): void {
$cur = $this->tail->next; // start at the head
for ($i = 0; $i < $passes; $i++) {
echo "Pass $i: " . $cur->val . " holds the parcel\n";
$cur = $cur->next; // after the tail we wrap to the head automatically
}
}
}
$circle = new CircularList();
foreach (['Mira', 'Kabir', 'Zoya', 'Aarav'] as $kid) $circle->append($kid);
echo implode(' -> ', $circle->oneLap()) . " -> (back to Mira)\n";
$circle->passParcel(6);JavaScript
class Node {
constructor(val) { this.val = val; this.next = null; }
}
class CircularList {
constructor() { this.tail = null; } // we keep the tail; the head is tail.next
append(val) {
const node = new Node(val);
if (this.tail === null) {
node.next = node; // a single node points to itself
} else {
node.next = this.tail.next; // new node points at the head
this.tail.next = node;
}
this.tail = node;
}
oneLap() { // visit every node exactly once
if (this.tail === null) return [];
const out = [];
const head = this.tail.next;
let cur = head;
do {
out.push(cur.val);
cur = cur.next;
} while (cur !== head); // stop when we are back at the start
return out;
}
passParcel(passes) {
let cur = this.tail.next; // start at the head
for (let i = 0; i < passes; i++) {
console.log('Pass ' + i + ': ' + cur.val + ' holds the parcel');
cur = cur.next; // after the tail we wrap to the head automatically
}
}
}
const circle = new CircularList();
for (const kid of ['Mira', 'Kabir', 'Zoya', 'Aarav']) circle.append(kid);
console.log(circle.oneLap().join(' -> ') + ' -> (back to Mira)');
circle.passParcel(6);Java
import java.util.*;
public class Main {
static class Node {
String val;
Node next = null;
Node(String val) { this.val = val; }
}
static class CircularList {
Node tail = null; // we keep the tail; the head is tail.next
void append(String val) {
Node node = new Node(val);
if (tail == null) {
node.next = node; // a single node points to itself
} else {
node.next = tail.next; // new node points at the head
tail.next = node;
}
tail = node;
}
List<String> oneLap() { // visit every node exactly once
List<String> out = new ArrayList<>();
if (tail == null) return out;
Node head = tail.next;
Node cur = head;
do {
out.add(cur.val);
cur = cur.next;
} while (cur != head); // stop when we are back at the start
return out;
}
void passParcel(int passes) {
Node cur = tail.next; // start at the head
for (int i = 0; i < passes; i++) {
System.out.println("Pass " + i + ": " + cur.val + " holds the parcel");
cur = cur.next; // after the tail we wrap to the head automatically
}
}
}
public static void main(String[] args) {
CircularList circle = new CircularList();
for (String kid : new String[]{"Mira", "Kabir", "Zoya", "Aarav"}) circle.append(kid);
System.out.println(String.join(" -> ", circle.oneLap()) + " -> (back to Mira)");
circle.passParcel(6);
}
}Go
package main
import (
"fmt"
"strings"
)
type Node struct {
val string
next *Node
}
type CircularList struct {
tail *Node // we keep the tail; the head is tail.next
}
func (c *CircularList) Append(val string) {
node := &Node{val: val}
if c.tail == nil {
node.next = node // a single node points to itself
} else {
node.next = c.tail.next // new node points at the head
c.tail.next = node
}
c.tail = node
}
// OneLap visits every node exactly once.
func (c *CircularList) OneLap() []string {
if c.tail == nil {
return nil
}
var out []string
head := c.tail.next
cur := head
for {
out = append(out, cur.val)
cur = cur.next
if cur == head { // stop when we are back at the start
break
}
}
return out
}
func (c *CircularList) PassParcel(passes int) {
cur := c.tail.next // start at the head
for i := 0; i < passes; i++ {
fmt.Printf("Pass %d: %s holds the parcel\n", i, cur.val)
cur = cur.next // after the tail we wrap to the head automatically
}
}
func main() {
circle := &CircularList{}
for _, kid := range []string{"Mira", "Kabir", "Zoya", "Aarav"} {
circle.Append(kid)
}
fmt.Println(strings.Join(circle.OneLap(), " -> ") + " -> (back to Mira)")
circle.PassParcel(6)
}Time: O(1) insert at either end, O(n) for a full lap · Extra space: O(n). Keeping the tail pointer makes both ends cheap, and wrapping around costs nothing.
Watch out for
- Looping with
while (cur.next !== null). A circular list has no null, so this never stops. - Using a plain
while (cur !== head)to walk one lap: it exits immediately because you start at the head. Use do-while (or step once first). - Forgetting the one-node case: the node must point to itself, not null.
Quick check
- In a circular singly linked list, what does the last node point to?
- null
- The first node
- The middle node
- Nothing, it has no next field
- Which loop is dangerous on a circular list?
- do ... while (cur !== head)
- for i in 0..n
- while (cur.next !== null)
- Stopping after counting n nodes
- If you keep only the tail pointer, how do you reach the head?
- tail.next
- tail.prev
- You cannot
- Walk the whole list