Doubly and circular linked lists
24 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)In a singly linked list, deleting a given node reference takes O(n) time unless you know its predecessor. Even with a tail pointer, removeLast() takes O(n) time. Adding prev creates a doubly linked list where inserting or removing any known node takes O(1) time.
Prev and next pointers
A doubly linked list is a chain of nodes where each node holds a value plus references to both the previous and the next node, so a known node can be unlinked in O(1).
Each node in a doubly linked list (DNode) stores three fields: int val, DNode prev, and DNode next.
Example 1 · Browser Tab History (back, forward, visit) Using a Doubly Linked List
public class BrowserHistoryDemo { static class PageNode { String url; PageNode prev, next; PageNode(String url) { this.url = url; } }
private PageNode curr;
public BrowserHistoryDemo(String homepage) { this.curr = new PageNode(homepage); }
public void visit(String url) { PageNode nextPage = new PageNode(url); curr.next = nextPage; // clears any old forward history! nextPage.prev = curr; curr = nextPage; }
public String back(int steps) { while (steps > 0 && curr.prev != null) { curr = curr.prev; steps--; } return curr.url; }
public String forward(int steps) { while (steps > 0 && curr.next != null) { curr = curr.next; steps--; } return curr.url; }
public static void main(String[] args) { BrowserHistoryDemo tab = new BrowserHistoryDemo("mentornxt.com"); tab.visit("docs.oracle.com"); tab.visit("openjdk.org"); System.out.println("Back 1: " + tab.back(1)); System.out.println("Back 1: " + tab.back(1)); System.out.println("Forward 1: " + tab.forward(1)); tab.visit("github.com"); // overwrites openjdk.org forward history System.out.println("Forward 2: " + tab.forward(2)); System.out.println("Back 2: " + tab.back(2)); }}Back 1: docs.oracle.com Back 1: mentornxt.com Forward 1: docs.oracle.com Forward 2: github.com Back 2: mentornxt.com
What this code does
- In Design Browser History,
backwalks.prev,forwardwalks.next, andvisitclearscurr.next. - Walking k steps backward or forward takes O(min(k, n)) time.
Suppose a method gives you a direct reference DNode node in the middle of a list to unlink. In a singly linked list, finding the node before node takes an O(n) walk from head. In a doubly linked list, node.prev and node.next sit right inside node. Unlinking node takes two assignments in O(1) time: node.prev.next = node.next; and node.next.prev = node.prev;. Walking backward from tail to head and removeLast() also run in O(1) per step.
Quick reference:
- Unlink
nodein O(1):node.prev.next = node.next; node.next.prev = node.prev;. - Insert
newNodebetweenleftandrightin O(1): setnewNode.prev = left; newNode.next = right; left.next = newNode; right.prev = newNode;. - Trade-off: each
DNodestores two links (prevandnext), adding 4 to 8 bytes per node.
Sentinel head and tail
Without dummy nodes, unlinking node needs four if checks for head, tail, and empty-list edge cases. A single missed null check throws NullPointerException.
- Allocate
head = new DNode(0)andtail = new DNode(0)in the constructor and wirehead.next = tail; tail.prev = head;. - Write one helper
insertBetween(DNode node, DNode left, DNode right)that wires all 4 pointers. - Write one helper
unlink(DNode node)that wiresnode.prev.next = node.nextandnode.next.prev = node.prevwith zeronullchecks.
Example 2 · Doubly Linked List With Sentinel Head and Tail (Zero Null Branches)
public class SentinelDoublyListDemo { static class DNode { int val; DNode prev, next; DNode(int val) { this.val = val; } }
static class DoublyLinkedList { private final DNode head = new DNode(0); private final DNode tail = new DNode(0);
DoublyLinkedList() { head.next = tail; tail.prev = head; }
private void insertBetween(DNode node, DNode left, DNode right) { node.prev = left; node.next = right; left.next = node; right.prev = node; }
public DNode addFirst(int val) { DNode node = new DNode(val); insertBetween(node, head, head.next); return node; }
public DNode addLast(int val) { DNode node = new DNode(val); insertBetween(node, tail.prev, tail); return node; }
public void unlink(DNode node) { node.prev.next = node.next; node.next.prev = node.prev; node.prev = node.next = null; }
public String formatForward() { StringBuilder sb = new StringBuilder("["); for (DNode c = head.next; c != tail; c = c.next) { if (c != head.next) sb.append(" <-> "); sb.append(c.val); } return sb.append("]").toString(); } }
public static void main(String[] args) { DoublyLinkedList dll = new DoublyLinkedList(); dll.addLast(10); DNode middle = dll.addLast(20); dll.addLast(30); dll.addFirst(5); System.out.println("Before unlink: " + dll.formatForward()); dll.unlink(middle); // O(1) removal by reference! System.out.println("After unlink(20): " + dll.formatForward()); }}Before unlink: [5 <-> 10 <-> 20 <-> 30] After unlink(20): [5 <-> 10 <-> 30]
What this code does
addFirst,addLast, andunlinkneed zeroifchecks becauseheadandtailsentinels guarantee non-null neighbors.- Holding the reference
middle(20) letsdll.unlink(middle)remove it in O(1) time without searching fromhead.
We can remove all boundary checks using two permanent sentinel (dummy) nodes: head and tail. An empty list starts as head.next = tail; tail.prev = head;. Every real data node sits strictly between head and tail (head <-> first <-> ... <-> last <-> tail). Because head and tail are never removed, every real node always has non-null node.prev and node.next!
head <-> ... <-> tail) forms half of the cache.Circular linked lists
In a circular linked list, the last node's .next pointer points back to head instead of null. In a circular doubly linked list, head.prev also points to tail.
Example 3 · Circular Singly Linked List: Round-Robin Task Ring
public class CircularListDemo { static class CNode { String name; CNode next; CNode(String name) { this.name = name; } }
private CNode tail;
public void addLast(String name) { CNode node = new CNode(name); if (tail == null) { node.next = node; tail = node; } else { node.next = tail.next; tail.next = node; tail = node; } }
public void printOneLap() { if (tail == null) return; CNode head = tail.next; CNode curr = head; StringBuilder sb = new StringBuilder(); do { sb.append(curr.name).append(" -> "); curr = curr.next; } while (curr != head); sb.append("(back to ").append(head.name).append(")"); System.out.println(sb); }
public static void main(String[] args) { CircularListDemo ring = new CircularListDemo(); ring.addLast("Worker-A"); ring.addLast("Worker-B"); ring.addLast("Worker-C"); ring.printOneLap(); }}Worker-A -> Worker-B -> Worker-C -> (back to Worker-A)
What this code does
- A single
tailpointer gives O(1) access to both the last node (tail) and first node (tail.next). - When inserting the very first node into an empty circular list,
node.next = nodeforms a 1-node ring.
Circular lists fit round-robin schedulers, where curr = curr.next wraps from the last task back to the first. In a circular singly linked list, a single tail pointer gives O(1) access to tail and head = tail.next. How do you traverse a circular list without looping forever? Since no node has .next == null, while (curr != null) spins forever. Instead, check if (head == null) return; and use do { ... curr = curr.next; } while (curr != head);.
Two rules for circular lists:
- Traversal stop condition: stop when
currreturns tohead(do { ... } while (curr != head)). - Insertion into sorted circular list: handle the wrap-around point where
curr.val > curr.next.val(from maximum back to minimum).
Next step
Check your understanding
10 quick questions