Course contentsShow
← C
Lesson 1004 of 1,21914. Data Structures in CFree lesson

Circular doubly linked lists

Circular doubly linked lists

What you'll learn: How to connect the ends of a doubly linked list to create an infinite loop that can be traversed in both directions.

Imagine a group of children standing in a line, each holding the hands of the person in front and behind them. If the first child and the last child reach out and grab each other’s free hands, they form a perfect circle. In C, this is a circular doubly linked list.

Closing the Loop

In a standard doubly linked list, the head->prev and tail->next pointers both point to NULL. This represents the "dead ends" of the chain. In a circular doubly linked list, we eliminate these dead ends.

Instead of NULL, the next pointer of the last node points back to the head. Simultaneously, the prev pointer of the head node points to the last node. This creates a seamless ring where you can cycle through data indefinitely without ever hitting a "stop" point.

Why use a circle?

Circular doubly linked lists are perfect for "Round Robin" scenarios. Think of the Alt + Tab switcher on your computer. You can move forward or backward through open windows, and if you keep going past the last window, you simply end up back at the first one. Because every node has a neighbor on both sides, you never have to reset your pointer to the beginning manually.

Conceptual Implementation

To turn a standard list into a circular one, you simply link the head and tail after your usual insertion logic:

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};

void makeCircular(struct Node* head, struct Node* tail) {
    if (head == NULL || tail == NULL) return;

    // The tail's next is no longer NULL; it goes to the start
    tail->next = head;

    // The head's prev is no longer NULL; it goes to the end
    head->prev = tail;
}

Traversal Warning

When working with these lists, a while(temp != NULL) loop will cause an infinite loop because NULL no longer exists! Instead, you typically save the starting node's address and stop when your moving pointer equals that address again.

Key takeaway

A circular doubly linked list connects the head and tail to each other, allowing for continuous forward and backward navigation without dead ends.