Circular Doubly Linked List
Example
function append(head, node) {
const tail = head.prev;
tail.next = node;
node.prev = tail;
}function append(head, node) {
const tail = head.prev;
tail.next = node;
node.prev = tail;
node.next = head;
head.prev = node;
}The new tail must link back to head, and head.prev must point to it, or the circle breaks.
Common mistakes
- Forgetting to update
head.prevwhen appending, so backward traversal skips the new tail. - Infinite loops from checking for
nullinstead of the start node.
Key points
- After every insert and delete,
head.previs the tail andtail.nextis the head. - A one-node list sets both
nextandprevto the node itself. - Traversal in either direction stops on returning to the start node.
Interview questions
Why use a circular doubly linked list instead of a doubly linked list?
You reach the tail from the head in O(1) through head.prev, and the ends need no null checks, which makes insert and delete simpler.
How do I get the last node of a circular doubly linked list?
Read head.prev. It always points to the tail, so no traversal is needed.
