Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Building a circular linked list in C

Implementing a circular linked list in C means replacing the usual NULL terminator with a link from the last node back to the first. Each node still holds a value and a pointer to its successor, but traversal stops when it reaches the starting node again. The structure suits round-robin scheduling, repeating playlists, token rings and other sequences that naturally wrap around.

C exposes allocation and pointer ownership directly, so the implementation must handle an empty list, a one-node list and allocation failure without leaking memory. A tail pointer simplifies insertion at the end, while a size counter helps callers track the number of elements. This suits the emphasis on pointer reasoning and complexity analysis common in Australian university and technical and further education courses.

The invariant is simple: in a non-empty list, tail->next is the head, and the last node points to that head. Every operation must preserve it. The code below follows Australian technical spelling, including “initialise” and “behaviour”, and covers insertion, traversal, search, deletion and cleanup.

Set up the node and list state

Start with one node type and one list structure. A singly linked node is enough because the operations only move forwards. The data structure guide is useful for comparing this representation with arrays, trees and other choices before committing to a design.

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

typedef struct Node {
    int value;
    struct Node *next;
} Node;

typedef struct {
    Node *tail;
    size_t size;
} CircularList;

void cl_init(CircularList *list)
{
    list->tail = NULL;
    list->size = 0;
}

Node *cl_new_node(int value)
{
    Node *node = malloc(sizeof *node);

    if (node == NULL) {
        return NULL;
    }

    node->value = value;
    node->next = NULL;
    return node;
}

The tail field identifies the final node; its next field is also the entry point to the ring. Storing only a head pointer would make appending awkward because the program would first have to find the last node.

For one node, next points to itself. For an empty list, tail is NULL and size is zero. Initialisation establishes those states, while cl_new_node keeps allocation and value assignment together.

Insert nodes at useful positions

Appending is constant-time because the tail is already known. The new node takes the old head as its successor, then the old tail points to the new node. When the list was empty, the new node points to itself.

int cl_push_back(CircularList *list, int value)
{
    Node *node = cl_new_node(value);

    if (node == NULL) {
        return -1;
    }

    if (list->tail == NULL) {
        node->next = node;
        list->tail = node;
    } else {
        node->next = list->tail->next;
        list->tail->next = node;
        list->tail = node;
    }

    list->size++;
    return 0;
}

int cl_push_front(CircularList *list, int value)
{
    Node *node = cl_new_node(value);

    if (node == NULL) {
        return -1;
    }

    if (list->tail == NULL) {
        node->next = node;
        list->tail = node;
    } else {
        node->next = list->tail->next;
        list->tail->next = node;
    }

    list->size++;
    return 0;
}

cl_push_front also runs in constant time because it can link the new node after the tail and before the head. Both functions return -1 when malloc fails, leaving the original list unchanged.

Insertion after a value is useful when a caller already holds a key. The search is linear, but the new link itself is constant-time. The first matching value is used when duplicates exist.

int cl_insert_after(CircularList *list, int after_value, int value)
{
    Node *current;

    if (list->tail == NULL) {
        return -1;
    }

    current = list->tail->next;

    do {
        if (current->value == after_value) {
            Node *node = cl_new_node(value);

            if (node == NULL) {
                return -1;
            }

            node->next = current->next;
            current->next = node;

            if (current == list->tail) {
                list->tail = node;
            }

            list->size++;
            return 0;
        }

        current = current->next;
    } while (current != list->tail->next);

    return -1;
}

Traverse and search the ring

Traversal needs a stopping rule because next never becomes NULL. Save the head pointer, visit at least one node, then continue until the cursor returns to that pointer. This also handles a single-node ring without a special counting loop.

void cl_print(const CircularList *list)
{
    const Node *current;

    if (list->tail == NULL) {
        printf("empty\n");
        return;
    }

    current = list->tail->next;

    do {
        printf("%d", current->value);

        if (current->next == list->tail->next) {
            printf("\n");
        } else {
            printf(" -> ");
        }

        current = current->next;
    } while (current != list->tail->next);
}

Search follows the same pattern and returns immediately on a match. If the cursor returns to the head without finding the key, the value is absent.

int cl_contains(const CircularList *list, int value)
{
    const Node *current;

    if (list->tail == NULL) {
        return 0;
    }

    current = list->tail->next;

    do {
        if (current->value == value) {
            return 1;
        }

        current = current->next;
    } while (current != list->tail->next);

    return 0;
}

A familiar Australian analogy is Melbourne’s City Circle Tram, which returns to its starting district rather than ending at a null stop. During an arvo coding meetup in Brisbane, that example could help explain why visiting the first element again means one complete revolution.

Remove nodes without breaking the ring

Deleting a node requires reconnecting its predecessor. A singly linked list has no backward pointer, so the function walks until it finds the first matching value and remembers the previous node.

int cl_remove(CircularList *list, int value)
{
    Node *head;
    Node *current;
    Node *previous = NULL;

    if (list->tail == NULL) {
        return -1;
    }

    head = list->tail->next;
    current = head;

    do {
        if (current->value == value) {
            if (head == list->tail) {
                free(current);
                list->tail = NULL;
                list->size = 0;
                return 0;
            }

            if (current == head) {
                list->tail->next = current->next;
            } else {
                previous->next = current->next;

                if (current == list->tail) {
                    list->tail = previous;
                }
            }

            free(current);
            list->size--;
            return 0;
        }

        previous = current;
        current = current->next;
    } while (current != head);

    return -1;
}

Head deletion advances tail->next; tail deletion moves the tail back one position; deleting the only node leaves the list empty. Removing the head in a multi-node ring therefore does not require changing the tail.

Cleanup must release every allocation exactly once. Starting at the head, the destroy function frees nodes until it reaches the tail, then frees the tail separately and resets the list state.

void cl_destroy(CircularList *list)
{
    Node *current;

    if (list->tail == NULL) {
        return;
    }

    current = list->tail->next;

    while (current != list->tail) {
        Node *next = current->next;
        free(current);
        current = next;
    }

    free(list->tail);
    list->tail = NULL;
    list->size = 0;
}

Returning a status from removal distinguishes an absent value from success, while allocation failures are handled separately during creation. This explicit ownership model is particularly valuable in longer C programs, where several lists or linked structures may coexist.

Apply the structure to realistic workloads

A circular list is valuable when elements receive recurring turns. Australian agriculture, mining, logistics and industrial-monitoring markets provide realistic settings for this pattern, where device software may run on constrained hardware alongside vendor tools or open-source controller projects. A rotating device list, worker list or event source can serve as a simple scheduling model. The structure is also a natural fit for classroom simulations of a round-robin CPU scheduler.

Graph algorithms offer another linked-structure lesson. For broader context, the Prim algorithm walkthrough explains how minimum spanning trees connect graph vertices. Prim’s algorithm normally uses adjacency lists and a priority queue, so a circular list is not a drop-in replacement, but it can model rotating adjacency entries or candidate edges in a teaching example.

A small driver can verify the basic behaviour. After these operations, the remaining values are 11, 13 and 15.

int main(void)
{
    CircularList list;
    int values[] = {7, 11, 15};
    size_t i;

    cl_init(&list);

    for (i = 0; i < sizeof values / sizeof values[0]; ++i) {
        if (cl_push_back(&list, values[i]) != 0) {
            cl_destroy(&list);
            return 1;
        }
    }

    if (cl_insert_after(&list, 11, 13) != 0) {
        cl_destroy(&list);
        return 1;
    }

    if (cl_remove(&list, 7) != 0) {
        cl_destroy(&list);
        return 1;
    }

    cl_print(&list);
    cl_destroy(&list);
    return 0;
}

Appending and prepending are O(1). Searching, inserting after a key and removing the first matching value are O(n) because they may scan the ring. Traversal and destruction are also O(n), while storage is O(n). A doubly linked circular list could make deletion from a known node constant-time, but it would require extra previous pointers and more maintenance.

Recommendations for a dependable implementation

The following practices reduce the most common defects in circular-list code:

The invariant provides the simplest acceptance test: after each operation, tail->next identifies the head, the last node closes the ring, and size matches the number of live nodes. Empty, singleton, duplicate and missing-value cases then exercise every branch that commonly breaks a circular list.