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.

Implementing a doubly linked list with sentinel nodes in C

A doubly linked list stores every value between two links: one to its predecessor and one to its successor. Sentinel nodes provide permanent boundary markers, allowing code to treat the front and rear much like ordinary positions. In C, where memory management is explicit, that consistency removes awkward empty-list branches and makes insertion, deletion, and traversal easier to reason about.

The design below embeds its head and tail sentinels inside the list object. Each sentinel has link fields but no meaningful payload. The list still has valid boundaries when it contains no data, and traversal never needs to special-case a missing node. This is a structural simplification, not a claim that a linked list beats every other container; random access and cache locality can still favour an array.

Within Australia's technology market, C is less prominent in many new product stacks than Python or Java, yet it remains useful in banking, logistics, embedded control, and mining software, particularly around Perth. Teams in Sydney and Melbourne also maintain fintech and freight products where predictable memory use can matter. The implementation therefore stays close to the C language while remaining useful for learning and for systems where pointer-level control is valuable.

Why sentinel nodes simplify boundary handling

Without sentinels, push_front must check for a null head, push_back must separately handle a null tail, and deleting the sole element needs another transition into the empty state. The site's data structures overview places linked lists alongside arrays and trees; within that family, sentinel nodes trade two reserved structures for uniform mutation logic.

Imagine a chain running from a left boundary to a right boundary. In an empty list, the left marker points to the right marker and the right marker points back. One payload node sits between them in a one-element list. In every state, head.next identifies the first real node, tail.prev identifies the last, and each payload node has one neighbour on either side.

This arrangement changes the algorithm's shape rather than its asymptotic cost. Searching still takes O(n) time, while linking or unlinking at a known position takes O(1). Every payload node has two non-NULL neighbour pointers, including when it is the first or last element; only head.prev and tail.next are NULL. The design reduces inconsistent null handling, but it does not protect against a programmer changing only one of the links that must be updated.

Defining the structure and its invariants

Use a payload appropriate to the application and treat sentinel payloads as irrelevant. An integer keeps the example compact, but a string handle, timestamp, or record pointer can occupy the same field. This C99-compatible structure embeds both boundary nodes in the list object:

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>

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

typedef struct {
    Node head;
    Node tail;
    size_t length;
} DoublyList;

void list_init(DoublyList *list)
{
    list->head = (Node){
        .value = 0,
        .prev = NULL,
        .next = &list->tail
    };
    list->tail = (Node){
        .value = 0,
        .prev = &list->head,
        .next = NULL
    };
    list->length = 0;
}

After initialisation, head.prev and tail.next are NULL, head.next points to tail, and tail.prev points to head. The length is zero. These conditions are invariants rather than setup details: they must be true before an operation and remain true when it returns, including after an allocation failure.

Embedding the markers makes ownership straightforward. The list owns every allocated payload node, while the sentinel nodes live inside the list object and must never be passed to free. Do not copy a DoublyList by assignment: its sentinel pointers would still refer to the original object's boundaries. Initialise a separate list and reinsert its values when a deep copy is required, and keep the list object at a stable address while it is in use.

Adding and traversing elements

Allocation is the first step in each insertion. If malloc fails, report failure without changing any links. Otherwise, connect the new node to its neighbours and redirect whichever adjacent node previously touched the boundary or the old neighbour.

bool list_push_front(DoublyList *list, int value)
{
    if (list->length == SIZE_MAX) {
        return false;
    }

    Node *node = malloc(sizeof *node);
    if (node == NULL) {
        return false;
    }

    node->value = value;
    node->prev = &list->head;
    node->next = list->head.next;
    list->head.next->prev = node;
    list->head.next = node;
    ++list->length;
    return true;
}

bool list_push_back(DoublyList *list, int value)
{
    if (list->length == SIZE_MAX) {
        return false;
    }

    Node *node = malloc(sizeof *node);
    if (node == NULL) {
        return false;
    }

    node->value = value;
    node->prev = list->tail.prev;
    node->next = &list->tail;
    list->tail.prev->next = node;
    list->tail.prev = node;
    ++list->length;
    return true;
}

bool list_contains(const DoublyList *list, int value)
{
    const Node *node = list->head.next;

    while (node != &list->tail) {
        if (node->value == value) {
            return true;
        }
        node = node->next;
    }

    return false;
}

The update order prevents a node from being skipped. In push_front, for example, head.next still identifies the former first node when its prev pointer is changed to the new node; only then does head.next point to the new node. The same pattern appears at the back. A search loop stops at the tail address, so the sentinel is never mistaken for payload.

Each traversal step is O(1), so visiting n values takes O(n) time and O(1) auxiliary space. A reverse loop can begin at tail.prev and stop at the head address. Inserting between two payload nodes follows the same local pattern: locate the predecessor, set the new links, and redirect both neighbours. The location search costs O(n), while the physical linking costs O(1). A saved node pointer must not be used after its node is removed because free invalidates it.

Removing values and releasing memory

Removal combines a linear search with a constant-time unlink. The function below removes the first matching value and leaves any duplicates in place. If no match exists, it returns false without changing the list.

bool list_remove(DoublyList *list, int value)
{
    Node *node = list->head.next;

    while (node != &list->tail && node->value != value) {
        node = node->next;
    }

    if (node == &list->tail) {
        return false;
    }

    node->prev->next = node->next;
    node->next->prev = node->prev;
    free(node);
    --list->length;
    return true;
}

void list_clear(DoublyList *list)
{
    Node *node = list->head.next;

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

    list->head.next = &list->tail;
    list->tail.prev = &list->head;
    list->length = 0;
}

The crucial assignments bypass the doomed node in both directions. Its predecessor's next pointer reaches its successor, and its successor's prev pointer reaches its predecessor. Removing the only payload node makes those neighbours the sentinels themselves, so the list returns directly to its empty state without a separate special case. list_clear similarly leaves the list object reusable; if the container itself was allocated on the heap, release it only after its payload nodes have been cleared.

Memory tooling is especially valuable here. Compile a debug build with AddressSanitizer, or run it under Valgrind, and exercise empty, one-element, head, tail, duplicate, and absent-value cases. If payload records identify customers, remember that the Privacy Act 1988 and Australian Privacy Principles can apply to the surrounding application. Freeing a node removes the local allocation, but it does not erase copies held in logs, backups, or downstream systems.

Practical recommendations for reliable C code

The implementation is compact, but dependable use depends on disciplined checks around allocation, mutation, and cleanup. These practices make failures visible early and keep the sentinel invariants intact.

Keep these rules active in ordinary engineering habits rather than treating them as optional polish. Australian teams often pair code reviews with white-board walkthroughs during stand-ups, mirroring the tap-on, tap-off rhythm of an Opal card in Sydney or a Myki in Melbourne: begin in a known state, perform one bounded transition, and verify the next state.

Local conventions can expose hidden errors. Debug logs may use the day-first DD/MM/YYYY date form and several Australian time zones, including AEST/AEDT and AWST, so an apparently incorrect sequence can reflect time-zone handling rather than list corruption. For a contrasting exercise in following updates, the site's shortest-path guide explains Floyd-Warshall's broader dependency pattern. Both examples reward explicit invariants, careful bounds, and repeatable tests. A sentinel-based list is then a small, dependable component with predictable ownership and behaviour.