Doubly Linked List in C, C++, Java, Python and C#: Sentinels, Circular Lists and O(1) Removal

How a sentinel node removes the boundary cases, why the second pointer makes removal O(1), and what circular lists buy in rotation and reverse walks.

A closed ring of pale gray beads joined by double threads, with one blue bead at the top and one bead lifted out on the left, its two former neighbors painted green and the ring closed between them.

A doubly linked list gives every node two pointers, so a node you already hold can be removed in constant time: no search, no previous-node walk. The catch is the boundary cases, where the first and last nodes have only one neighbor. The fix is one sentinel node that closes the list into a ring. Over the same 200,000 operations in the experiment below, the sentinel version evaluated 233,456 conditionals against 433,456 for the head/tail version, 200,000 fewer, with the same output. Closing the ring also makes rotation cheap: 10,000 rotate-left operations on 100,000 values took 0.05 ms in the circular list against 82.76 ms in a contiguous array.

This guide implements a circular doubly linked list with one sentinel in C, C++, Java, Python and C#. It covers the operations that need the backward pointer: O(1) removal of a held node, insertion before and after a known node, reverse traversal, and rotation. It then measures the sentinel design against the null-checked alternative and rotation against an array, and compares the hand-written list with std::list and std::deque. The Linked List in C page covers the singly linked list, so this article focuses on what the second pointer buys.

Every program was built and tested on Ubuntu 24.04 under WSL2 and on Windows 11 with MSVC, Java, Python and .NET, and every output block below comes from a real run.

What Is a Doubly Linked List?

A doubly linked list is a chain of nodes where each node stores a value and two links, one to the previous node and one to the next. The backward link is what makes removal of a node you already hold an O(1) pointer update, and it is what makes reverse traversal possible without reversing the list first.

A singly linked list node stores a value and a next pointer. Removing the node after a known node costs O(1), but removing the known node itself needs its predecessor, which means a search from the head. The doubly linked node carries the predecessor, so removing it touches exactly two neighbors: node.prev.next = node.next and node.next.prev = node.prev. That property is why the structure appears inside caches. A hash table locates the entry, the list keeps the entries ordered, and a hit moves the entry to the front with a few pointer writes. The LRU and FIFO cache simulator is the working example of that combination.

The cost is one extra pointer of memory per node and one extra pointer write per insertion or removal. The list also loses the cheap array property: reaching the k-th element is O(k), not O(1), and the nodes are scattered in memory, so walking the list is slower than walking an array of the same size even though both are O(n). The measured section compares the hand-written list with std::list and std::deque for exactly that reason.

The boundary cases are the part the plain version gets wrong. A linear list with head and tail pointers must test for an empty list on every insertion and every removal. It must also keep the two pointers consistent, because adding to an empty list or removing the only node has to update both ends at once.

A circular list with one sentinel node removes both pointers and both tests: the sentinel is always present, sentinel.next is the first value, sentinel.prev is the last, and the empty list is the ring with the sentinel pointing at itself. Every operation becomes the same pointer writes whether the list is empty, has one node, or has a million.

One sentinel, no boundary cases Every real node has a neighbor on both sides, even the first and the last. S 10 20 30 sentinel sentinel.next sentinel.prev S empty next = prev = S Dark arrows follow next, and gray arrows follow prev. The sentinel is never a stored value. No NULL, no separate head or tail pointer, and the empty ring is the same shape.
Figure 1: The circular list as a ring: a blue sentinel that is never a stored value, three nodes, and two arrows between every pair, one for next and one for prev. The inset is the empty list, where the sentinel points to itself in both directions, so no operation needs a NULL check.

How This Was Measured

SettingValue
Date testedDecember 1, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39; Windows 11 for the MSVC, Java and .NET builds
CompilersGCC 13.3 and Clang 18.1.3 at -O2 and -O3 through CMake Release; MSVC 19.44 at /W4 /WX
Language runtimesOpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404
Branch experimentTwo list implementations behind identical operations, the same deterministic 200,000-operation workload each; conditionals counted inside the list functions only
Rotation experiment100,000 values, 10,000 rotate-left-by-one operations, circular sentinel list against a contiguous array with memmove
Standard-library benchmark1,000,000 push_back, a forward sum and 1,000,000 pop_front, median of 5 runs, custom list against std::list and std::deque
What is timedThe list operations only; workload selection and verification are outside the timed regions
StatisticSingle run for the C experiments, median of 5 for the C++ benchmark, milliseconds
CheckThe two list variants must produce the same values and checksum; the rotation structures must agree on their final checksum

No CPU pinning or frequency scaling control was used, and the host runs other software, so timings are indicative for this machine and the ratios are the useful part. All numbers come from one machine and one WSL2 instance. The branch counter is placed by hand around each conditional inside the list code, so it measures conditional evaluations, not machine-level branch instructions. The README of the C example states exactly which functions are instrumented.

The Sentinel Ring: One Node to Remove Every Special Case

The core of the implementation is four pointer writes. Inserting a new node after a known node p is: q = p.next, new.next = q, new.prev = p, p.next = new, q.prev = new. Inserting before p is the same with the roles of prev and next exchanged. Removing a node x is two writes: x.prev.next = x.next and x.next.prev = x.prev, then freeing or returning it. None of these look at the head, the tail or a size, because the sentinel is just another node and the ring never has a missing neighbor.

The operations built on those four writes are equally uniform. Push_back inserts before the sentinel and push_front inserts after it. Front and back read sentinel.next and sentinel.prev, and pop_front and pop_back remove those two nodes. Remove_node takes a node handle and unlinks it in O(1). Rotate_left(k) moves the first k nodes to the end with pointer writes only, and no value moves. The forward walk stops at the sentinel, and the reverse walk starts at sentinel.prev and follows prev back to the sentinel.

The null-checked alternative needs a branch on every one of those operations. Push_back tests whether tail is null, pop_front tests whether the list is empty, and the single-element removal has to reset both head and tail. Those are the branches the experiment counts.

push_back: one branch or none The null-terminated list asks whether the list is empty; the sentinel ring does not. head/tail list new = node(v) tail == NULL? empty: head = tail = new not empty: tail.next = new then: new.prev = tail; tail = new one conditional per push_back, plus the empty case for pop sentinel ring new.prev = sentinel.prev new.next = sentinel sentinel.prev.next = new sentinel.prev = new no conditional the same four writes on every push_back
Figure 2: push_back in the two designs. The null-terminated list asks whether the list is empty and then follows one of two assignment paths; the sentinel ring always performs the same four pointer writes. The measured version of this difference is Figure 3.

Doubly Linked List Implementation in C

The C version keeps the sentinel as an embedded node in the list structure, so the list needs no allocation for its own head, and every real node is allocated and freed by the list. The node handle is a DlNode * returned by dlist_find.

static void link_before(DlNode *node, DlNode *before)
{
    node->prev = before->prev;
    node->next = before;
    before->prev->next = node;
    before->prev = node;
}

/* Unlinks node from the ring: the two pointer writes that remove it. The node
 * itself is left untouched so the caller decides whether to free it. */
static void unlink_node(DlNode *node)
{
    node->prev->next = node->next;
    node->next->prev = node->prev;
}
bool dlist_push_back(DlList *list, int value)
{
    DlNode *node = node_new(value);
    if (node == NULL)
        return false;
    link_before(node, &list->sentinel);
    list->size++;
    return true;
}

bool dlist_push_front(DlList *list, int value)
{
    DlNode *node = node_new(value);
    if (node == NULL)
        return false;
    link_before(node, list->sentinel.next);
    list->size++;
    return true;
}

bool dlist_front(const DlList *list, int *value)
{
    if (list->size == 0)
        return false;
    *value = list->sentinel.next->value;
    return true;
}

bool dlist_back(const DlList *list, int *value)
{
    if (list->size == 0)
        return false;
    *value = list->sentinel.prev->value;
    return true;
}

bool dlist_pop_front(DlList *list, int *value)
{
    DlNode *first;
    if (list->size == 0)
        return false;
    first = list->sentinel.next;
    *value = first->value;
    unlink_node(first);
    free(first);
    list->size--;
    return true;
}

bool dlist_pop_back(DlList *list, int *value)
{
    DlNode *last;
    if (list->size == 0)
        return false;
    last = list->sentinel.prev;
    *value = last->value;
    unlink_node(last);
    free(last);
    list->size--;
    return true;
}
void dlist_rotate_left(DlList *list, size_t count)
{
    size_t steps = list->size == 0 ? 0 : count % list->size;
    while (steps > 0) {
        DlNode *first = list->sentinel.next;
        unlink_node(first);
        link_before(first, &list->sentinel);
        steps--;
    }
}

The four writes appear as link_before and unlink_node helpers, and every public function is a few calls to them. Once the helpers are right, the boundary cases disappear. The tests check the ring invariants after every batch of operations: sentinel.next->prev == sentinel, sentinel.prev->next == sentinel, and every node’s prev->next == node.

Output:

circular doubly linked list with a sentinel
push_back 30, 10, 20 -> size 3, forward: 30 10 20
push_front 5 -> size 4, forward: 5 30 10 20
front 5, back 20
remove 30 -> size 3, forward: 5 10 20, reverse: 20 10 5
insert_before 10 value 7 -> size 4, forward: 5 7 10 20
pop_front -> 5, size 3, forward: 7 10 20
pop_back -> 20, size 2, forward: 7 10
rotate_left 1 -> forward: 10 7
clear -> size 0, empty true

Doubly Linked List Implementation in C++

The C++ version is a template with one sentinel node owned by the list and real nodes allocated by the list. Handles are pointers to nodes, so remove_node is O(1) and the iterator-style access is the raw node pointer. The class frees every node in its destructor, including the nodes of a list that was never cleared.

    static void attach_before(Link* position, Link* node) noexcept
    {
        node->prev = position->prev;
        node->next = position;
        position->prev->next = node;
        position->prev = node;
    }

    // Unlinks node from its two neighbours. The sentinel guarantees that both
    // neighbours exist, so there is no head, tail or single-node case.
    static void detach(Link* node) noexcept
    {
        node->prev->next = node->next;
        node->next->prev = node->prev;
    }
    void push_back(const T& value) { attach_before(&sentinel_, new Node(value)); ++size_; }
    void push_front(const T& value) { attach_before(sentinel_.next, new Node(value)); ++size_; }

    // The first and the last value. Both throw std::out_of_range when the list
    // is empty rather than reading the sentinel.
    [[nodiscard]] const T& front() const
    {
        require_non_empty("front");
        return static_cast<const Node*>(sentinel_.next)->value;
    }

    [[nodiscard]] const T& back() const
    {
        require_non_empty("back");
        return static_cast<const Node*>(sentinel_.prev)->value;
    }
    bool remove_node(iterator position) noexcept
    {
        if (position == end())
            return false;
        Link* link = position.link_;
        detach(link);
        delete static_cast<Node*>(link);
        --size_;
        return true;
    }

    // Moves the first k values to the end in O(k) steps. k == 0 and every
    // multiple of size() leave the list unchanged, and an empty list ignores k.
    void rotate_left(std::size_t k)
    {
        if (size_ == 0)
            return;
        k %= size_;
        if (k == 0)
            return;
        Link* block_first = sentinel_.next;
        Link* block_last = block_first;
        for (std::size_t step = 1; step < k; ++step)
            block_last = block_last->next;
        Link* rest_first = block_last->next;
        Link* old_last = sentinel_.prev;
        // Unplug the block from the front, then plug it behind the old last
        // node. The sentinel's links are the only ones that move.
        sentinel_.next = rest_first;
        rest_first->prev = &sentinel_;
        old_last->next = block_first;
        block_first->prev = old_last;
        block_last->next = &sentinel_;
        sentinel_.prev = block_last;
    }

std::list is the standard container: a doubly linked list with O(1) insert and erase given an iterator, splice for moving whole runs between lists, and no random access. libstdc++ builds it around a header node that works like the sentinel here. Erasing invalidates only the erased iterator, and erase returns the next one. The fifth pitfall shows what happens when code keeps using the erased iterator. The cppreference page lists the full interface.

Doubly Linked List Implementation in Java, Python and C#

The three versions follow the ring design, with a private sentinel node and public node handles. Their standard libraries differ in what they provide, and in one case the obvious candidate is not a linked list at all.

Java

    private void linkBetween(Node<E> predecessor, Node<E> successor, E value) {
        Node<E> node = new Node<>(value);
        node.prev = predecessor;
        node.next = successor;
        predecessor.next = node;
        successor.prev = node;
        node.owner = this;
        size++;
    }

    /** Unlinks a live node and returns its value. */
    private E unlink(Node<E> node) {
        E value = node.value;
        node.prev.next = node.next;
        node.next.prev = node.prev;
        node.prev = null;
        node.next = null;
        node.owner = null;
        size--;
        return value;
    }
    public void rotateLeft(int k) {
        if (k < 0) {
            throw new IllegalArgumentException("negative rotation: " + k);
        }
        if (size < 2) {
            return;
        }
        int shift = k % size;
        if (shift == 0) {
            return;
        }
        Node<E> oldFirst = sentinel.next;
        Node<E> newFirst = oldFirst;
        for (int step = 0; step < shift; step++) {
            newFirst = newFirst.next;
        }
        Node<E> lastMoved = newFirst.prev;
        Node<E> oldLast = sentinel.prev;
        sentinel.next = newFirst;
        newFirst.prev = sentinel;
        oldLast.next = oldFirst;
        oldFirst.prev = oldLast;
        lastMoved.next = sentinel;
        sentinel.prev = lastMoved;
    }

CircularList is generic over E, keeps the sentinel private, exposes a Node handle from find, and implements the contract’s operations including rotateLeft. Its tests compare every operation against a list model and check the ring invariants. Java’s own LinkedList is a doubly linked list that also implements Deque and List. Its listIterator gives the backward traversal, and remove on the iterator is O(1).

Python

    def _insert_after(self, node: Node[T], value: T) -> None:
        """Link a new node holding value directly after node."""
        new_node = Node(value)
        new_node.next = node.next
        new_node.prev = node
        node.next.prev = new_node
        node.next = new_node
        new_node._linked = True
        self._size += 1

    def _insert_before(self, node: Node[T], value: T) -> None:
        """Link a new node holding value directly before node."""
        new_node = Node(value)
        new_node.prev = node.prev
        new_node.next = node
        node.prev.next = new_node
        node.prev = new_node
        new_node._linked = True
        self._size += 1

    def _unlink(self, node: Node[T]) -> None:
        """Remove a linked node in O(1) and mark its handle dead."""
        node.prev.next = node.next
        node.next.prev = node.prev
        node.prev = node
        node.next = node
        node._linked = False
        self._size -= 1
    def rotate_left(self, k: int) -> None:
        """Move the first k values to the end, in O(k) pointer work.

        A value of 0 or a multiple of the size changes nothing.  A negative k
        rotates to the right by the same rule.  The relative order of the nodes
        never changes: only the sentinel is re-seated between the k-th and the
        k+1-th node, which is what makes one rotation six pointer writes.
        """
        if self._size < 2:
            return
        steps = k % self._size
        if steps == 0:
            return
        sentinel = self._sentinel
        old_first = sentinel.next
        old_last = sentinel.prev
        new_last = old_first
        for _ in range(steps - 1):
            new_last = new_last.next
        new_first = new_last.next
        # The two cut neighbours of the old sentinel position become adjacent.
        old_last.next = old_first
        old_first.prev = old_last
        # Re-seat the sentinel between the k-th and the k+1-th node.
        sentinel.next = new_first
        new_first.prev = sentinel
        sentinel.prev = new_last
        new_last.next = sentinel

The Python CircularList stores node objects with value, prev and next, returns the node from find, and keeps the sentinel as a private node. The tests compare against a plain list model and verify the ring after churn. Python’s standard library has no linked list type: collections.deque is a block-based deque with O(1) operations at both ends and O(n) in the middle, and a hand-written list is the alternative when O(1) middle removal of a held node matters.

C#

    private void LinkAfter(Node previous, Node node)
    {
        Node next = previous.Next!;
        node.Owner = this;
        node.Prev = previous;
        node.Next = next;
        previous.Next = node;
        next.Prev = node;
        _count++;
    }

    // Removes a linked node and clears its links, so the handle cannot be used
    // to reach the ring it just left.
    private void Unlink(Node node)
    {
        node.Prev!.Next = node.Next;
        node.Next!.Prev = node.Prev;
        node.Owner = null;
        node.Prev = null;
        node.Next = null;
        _count--;
    }
    public void RotateLeft(int k)
    {
        if (k < 0)
            throw new ArgumentOutOfRangeException(nameof(k), k, "The rotation count cannot be negative.");
        if (_count < 2)
            return;

        k %= _count;
        if (k == 0)
            return;

        // Walk to the last moved node, then cut the ring after it.
        Node lastMoved = _sentinel.Next!;
        for (int step = 1; step < k; step++)
            lastMoved = lastMoved.Next!;

        Node firstMoved = _sentinel.Next!;
        Node newFirst = lastMoved.Next!;
        Node oldLast = _sentinel.Prev!;

        // The sentinel now sits between the old last node and the new first
        // node, and the two cut ends are joined to close the ring again.
        _sentinel.Next = newFirst;
        newFirst.Prev = _sentinel;
        _sentinel.Prev = lastMoved;
        lastMoved.Next = _sentinel;
        oldLast.Next = firstMoved;
        firstMoved.Prev = oldLast;
    }

The C# CircularList<T> uses a private sentinel and a Node handle, with AddFirst, AddLast, RemoveFirst, RemoveLast, InsertBefore, InsertAfter, RemoveNode, RemoveValue, RotateLeft, Forward, Reverse and Clear. The BCL’s LinkedList<T> is a doubly linked list with LinkedListNode<T> handles, AddFirst, AddLast, AddBefore, AddAfter, Remove(node) and RemoveFirst/RemoveLast. It is the closest standard equivalent to the class here.

Where the Standard Libraries Land

LanguageContainerKindNode handleO(1) removal by handleReverse walk
Cnoneimplement itpointeryes, with this codeyes
C++std::listdoubly linked listiteratoryes, erase(it)yes, reverse iterators
JavaLinkedListdoubly linked listListIteratoryes, iterator removeyes, descendingIterator
Pythoncollections.dequeblock array, not a linked listnonenoyes, reverse or reversed
C#LinkedList<T>doubly linked listLinkedListNode<T>yes, Remove(node)yes, Last then Previous

The table explains the two common mistakes. Python’s deque looks like the standard doubly linked list and is not one. It is fast at the ends and linear in the middle, and it has no node handles. Every real linked list here exposes a node or iterator handle, because the O(1) removal is only O(1) when the caller already holds the node. remove(value) still has to find it.

The Sentinel Against the Null Checks: Measured Branches

The branch experiment builds two lists behind the same operations: the circular sentinel ring from this article and a head/tail list with null checks. Both run the same deterministic 200,000-operation workload, and both must end with the same values and checksum. The counter is incremented at every conditional inside the list functions.

static BranchNode *sentinel_push_back(void *state, int value)
{
    SentinelRing *list = state;
    BranchNode *node = branch_node_new(value);
    sentinel_link_before(node, &list->sentinel);
    list->size++;
    return node;
}

static BranchNode *sentinel_push_front(void *state, int value)
{
    SentinelRing *list = state;
    BranchNode *node = branch_node_new(value);
    sentinel_link_before(node, list->sentinel.next);
    list->size++;
    return node;
}
static BranchNode *null_push_back(void *state, int value)
{
    NullList *list = state;
    BranchNode *node = branch_node_new(value);
    node->prev = list->tail;
    node->next = NULL;
    if (COUNTED(list->tail != NULL))
        list->tail->next = node;
    else
        list->head = node;
    list->tail = node;
    list->size++;
    return node;
}

Output:

200,000 operations, identical results
variant   branch_checks  time_ms  checksum
sentinel  233456         5        5624354460455916176
null      433456         4        5624354460455916176

The sentinel ring evaluated 233,456 conditionals over the 200,000 operations, and the head/tail list evaluated 433,456. The difference is exactly 200,000, one extra conditional per operation. The null version tests whether a push touches the first node and whether a pop empties an end, while the sentinel version’s writes are unconditional on every push. Both variants ended with the same values and the same checksum 5,624,354,460,455,916,176.

The time column, 5 ms for the sentinel and 4 ms for the null list, is noise at this size and is not a result. The branch count is the reproducible difference, and the real gain is the code paths that disappear, because the empty, first and last cases stop being special cases.

Conditional evaluations for the same 200,000 operations Counted inside the list functions only, not in the workload loop. sentinel ring 233,456 head/tail null 433,456 The null list evaluates 200,000 more conditionals, 1.00 per operation; times were 5.0 ms and 4.0 ms on this machine. The branch is not the whole cost; it is the visible difference between the two designs.
Figure 3: Conditional evaluations inside the list functions for the same 200,000-operation workload, sentinel ring against the head/tail null list. The sentinel design removes the empty-list tests, and the bars show what that is worth on this machine.

Rotating a Circular List

Rotation is where the ring is more than cosmetics. Rotating a linked list left by one detaches the first node and appends it, an unlink and a link of six pointer writes with the sentinel. The values never move and the cost does not depend on the list length. The same rotation on a contiguous array has to shift every element, so the array’s cost grows with n. The experiment does 10,000 rotations of a 100,000-value list and of the same values in an array.

int main(void)
{
    DlList list;
    int *array = malloc((size_t)VALUE_COUNT * sizeof *array);
    int *walk = malloc((size_t)VALUE_COUNT * sizeof *walk);
    unsigned long long list_sum = FNV_OFFSET;
    unsigned long long array_sum = FNV_OFFSET;
    double list_ms;
    double array_ms;
    double started;
    size_t index;
    size_t count;

    if (array == NULL || walk == NULL) {
        free(array);
        free(walk);
        fputs("out of memory\n", stderr);
        return EXIT_FAILURE;
    }

    dlist_init(&list);
    for (index = 0; index < (size_t)VALUE_COUNT; ++index) {
        int value = initial_value(index);
        array[index] = value;
        if (!dlist_push_back(&list, value)) {
            fputs("out of memory\n", stderr);
            dlist_clear(&list);
            free(array);
            free(walk);
            return EXIT_FAILURE;
        }
    }

    started = now_ms();
    for (index = 0; index < (size_t)ROTATION_COUNT; ++index)
        dlist_rotate_left(&list, 1);
    list_ms = now_ms() - started;

    started = now_ms();
    for (index = 0; index < (size_t)ROTATION_COUNT; ++index) {
        int first = array[0];
        memmove(&array[0], &array[1],
                ((size_t)VALUE_COUNT - 1) * sizeof *array);
        array[VALUE_COUNT - 1] = first;
    }
    array_ms = now_ms() - started;

    count = dlist_forward(&list, walk, (size_t)VALUE_COUNT);
    if (count != (size_t)VALUE_COUNT) {
        fputs("the list lost values during rotation\n", stderr);
        dlist_clear(&list);
        free(array);
        free(walk);
        return EXIT_FAILURE;
    }
    for (index = 0; index < count; ++index) {
        list_sum = checksum_add(list_sum, walk[index]);
        array_sum = checksum_add(array_sum, array[index]);
    }
    dlist_clear(&list);
    free(walk);
    free(array);

    if (list_sum != array_sum) {
        fputs("the list and the array ended on different sequences\n", stderr);
        return EXIT_FAILURE;
    }

    printf("100,000 values, 10,000 left rotations\n");
    printf("%-19s%-11s%s\n", "structure", "rotate_ms", "checksum");
    printf("%-19s%-11.2f%llu\n", "circular sentinel", list_ms, list_sum);
    printf("%-19s%-11.2f%llu\n", "contiguous array", array_ms, array_sum);
    return EXIT_SUCCESS;
}

Output:

100,000 values, 10,000 left rotations
structure          rotate_ms  checksum
circular sentinel  0.05       1273883504485815623
contiguous array   82.76      1273883504485815623

The circular list finished 10,000 rotations in 0.05 ms, and the contiguous array needed 82.76 ms, more than 1,600 times longer. Each array rotation moves 99,999 ints (about 400 KB) while the list writes six pointers. The array’s per-rotation cost grows with the list length and the list’s does not. Both structures ended on checksum 1,273,883,504,485,815,623, so the comparison is on identical sequences. For round-robin scheduling or any workload that rotates a sequence forever, that is the difference between O(k) pointer work and O(n) data movement per rotation.

Custom List Against std::list and std::deque

The C++ benchmark pushes 1,000,000 values onto the back, sums them in a forward walk, then pops them from the front, for the hand-written sentinel list, std::list and std::deque.

int main()
{
    const RunResult custom = median_of_runs<CircularList<int>>();
    const RunResult standard_list = median_of_runs<std::list<int>>();
    const RunResult deque = median_of_runs<std::deque<int>>();

    std::printf(
        "1,000,000 push_back + forward sum + pop_front, median of 5 runs (ms)\n");
    std::printf("%-20s  %.1f\n", "custom sentinel list", custom.milliseconds);
    std::printf("%-20s  %.1f\n", "std::list", standard_list.milliseconds);
    std::printf("%-20s  %.1f\n", "std::deque", deque.milliseconds);
    std::printf("checksum: %llu\n",
                static_cast<unsigned long long>(custom.checksum));

    if (custom.checksum != standard_list.checksum ||
        custom.checksum != deque.checksum) {
        std::fprintf(stderr,
                     "checksum mismatch: custom %llu, std::list %llu, std::deque %llu\n",
                     static_cast<unsigned long long>(custom.checksum),
                     static_cast<unsigned long long>(standard_list.checksum),
                     static_cast<unsigned long long>(deque.checksum));
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Output:

1,000,000 push_back + forward sum + pop_front, median of 5 runs (ms)
custom sentinel list  24.7
std::list             26.2
std::deque            3.9
checksum: 6430232365601476

On 1,000,000 push_back, a forward sum and 1,000,000 pop_front, the custom sentinel list took 24.7 ms, std::list took 26.2 ms, and std::deque took 3.9 ms. The custom list is a little faster than std::list, so the sentinel design costs nothing detectable. The deque is about six times faster than either list, because it allocates in blocks of contiguous elements while each list node is a separate allocation the walk must chase. All three produced checksum 6,430,232,365,601,476. The linked list pays for scattered nodes on every walk, and it earns that back only when the workload moves nodes rather than walking them.

Five Ways a Doubly Linked List Passes a Quick Test and Still Fails

Each of these programs compiles cleanly with -Wall -Wextra -pedantic and prints something plausible until the line below it. The first four live in the C repository’s pitfalls/ directory and the fifth in the C++ repository’s, and the workflows re-run each and assert the line or sanitizer summary that shows the bug.

static void remove_node_broken(List *list, Node *node)
{
    node->next->prev = node->prev;
    free(node);
    list->size--;
}

/* The ordinary forward walk, which follows next until it reaches the
 * sentinel. After the broken removal it reaches the freed node first. */
static void print_forward(const List *list)
{
    const Node *node;
    for (node = list->sentinel.next; node != &list->sentinel;
         node = node->next) {
        printf(" %d", node->value);
    }
}

int main(void)
{
    List list;
    Node *node;
    static const int values[] = { 10, 20, 30, 40, 50 };
    size_t index;

    setvbuf(stdout, NULL, _IONBF, 0);
    puts("broken_unlink: remove_node updates only the next node's prev pointer");
    list_init(&list);
    for (index = 0; index < sizeof values / sizeof values[0]; ++index)
        push_back(&list, values[index]);
    printf("list:");
    print_forward(&list);
    putchar('\n');

    node = find(&list, 30);
    if (node == NULL) {
        fputs("the value 30 is missing\n", stderr);
        return EXIT_FAILURE;
    }
    remove_node_broken(&list, node);
    printf("remove_node(30) freed the node, size %zu\n", list.size);
    printf("forward walk (expect 10 20 40 50):");
    print_forward(&list);
    putchar('\n');
    return EXIT_SUCCESS;
}

Output:

broken_unlink: remove_node updates only the next node's prev pointer
list: 10 20 30 40 50
remove_node(30) freed the node, size 4
forward walk (expect 10 20 40 50): 10 20

Output (summarized from the AddressSanitizer report):

AddressSanitizer: heap-use-after-free
READ of size 4 at pitfalls/broken_unlink.c:88 (print_forward)
24-byte region freed by remove_node_broken at pitfalls/broken_unlink.c:77
allocated by node_new at pitfalls/broken_unlink.c:30
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/broken_unlink.c:88 in print_forward

The remove helper fixes the next node’s prev pointer and forgets the previous node’s next pointer, so the ring still reaches the freed node on the forward walk. The program prints the list, removes 30, prints the first two nodes, and then AddressSanitizer aborts with a heap-use-after-free on the freed 24-byte region. The size still said 4, the forward walk looked half right, and the only visible clue was a missing node. Both neighbor pointers must be rewritten before the node is freed.

2. Walking Past the Sentinel

static size_t walk_to_sentinel(const List *list, int *values, size_t capacity)
{
    const Node *node = list->sentinel.next;
    size_t count = 0;
    while (node != &list->sentinel && count < capacity) {
        values[count] = node->value;
        count++;
        node = node->next;
    }
    return count;
}

/* The bug: the loop tests node != NULL. Inside a ring the sentinel is always
 * next, so the test is never false and the walk visits the ring again. */
static size_t walk_stopping_at_null(const List *list, int *values,
                                    size_t capacity)
{
    const Node *node = list->sentinel.next;
    size_t count = 0;
    while (node != NULL && count < capacity) {
        values[count] = node->value;
        count++;
        node = node->next;
    }
    return count;
}

Output:

sentinel_skip: the forward walk stops at NULL, but the ring has none
list: 10 20 30 40
walk stopping at NULL after 10 steps: 10 20 30 40 -1 10 20 30 40 -1
expected: 10 20 30 40

A forward loop that stops at NULL works on a null-terminated list and never terminates on the ring, because there is no NULL: the walk goes round and round. The bounded version records 10 20 30 40 -1 10 20 30 40 -1, where the correct output is 10 20 30 40, and -1 marks the sentinel value that should have stopped the walk. In a ring the sentinel is the terminator, and every loop has to compare against it explicitly.

3. The Stale Tail Pointer

static void cache_remove_last(CachedTail *cache)
{
    Node *last = cache->list->sentinel.prev;
    last->prev->next = &cache->list->sentinel;
    cache->list->sentinel.prev = last->prev;
    free(last);
    cache->list->size--;
}

/* The cached back(): it trusts the cache instead of asking the list. */
static bool cache_back(const CachedTail *cache, int *value)
{
    *value = cache->tail->value;
    return true;
}

Output:

stale_tail: the cached tail pointer is not refreshed after a removal
list: 10 20 30
removed the last node 30, size 2, cached tail still points at it
cached back() reads the freed node:

Output (summarized from the AddressSanitizer report):

AddressSanitizer: heap-use-after-free
READ of size 4 at pitfalls/stale_tail.c:95 (cache_back)
24-byte region freed by cache_remove_last at pitfalls/stale_tail.c:88
allocated by node_new at pitfalls/stale_tail.c:36
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/stale_tail.c:95 in cache_back

A cached tail pointer saves a sentinel.prev read on back(), and this one is not refreshed when the last node is removed: it keeps pointing at the freed 24-byte region. Back() reads the freed node and AddressSanitizer reports heap-use-after-free. The fix is either to update the cache in the remove helper or to drop the cache and read sentinel.prev, which is already O(1). With a sentinel the cache saves nothing, so dropping it is the better fix.

4. push_front That Forgets the Old First Node

static void push_front_broken(List *list, int value)
{
    Node *node = node_new(value);
    node->prev = &list->sentinel;
    node->next = list->sentinel.next;
    list->sentinel.next = node;
    list->size++;
}

static void list_clear(List *list)
{
    Node *node = list->sentinel.next;
    while (node != &list->sentinel) {
        Node *next = node->next;
        free(node);
        node = next;
    }
    list_init(list);
}

static void print_forward(const List *list)
{
    const Node *node;
    for (node = list->sentinel.next; node != &list->sentinel;
         node = node->next) {
        printf(" %d", node->value);
    }
}

static void print_reverse(const List *list)
{
    const Node *node;
    for (node = list->sentinel.prev; node != &list->sentinel;
         node = node->prev) {
        printf(" %d", node->value);
    }
}

Output:

push_front_forgets_prev: push_front skips the old first node's prev
after push_back 10 20 30 and push_front 5, size 4
forward: 5 10 20 30
reverse: 30 20 10, expected 30 20 10 5

Push_front links the new node after the sentinel and forgets that the previous first node’s prev must point at the new node. The forward walk is correct, 5 10 20 30, and the reverse walk is wrong: 30 20 10, missing 5, because the old first node still points at the sentinel on the way back. The ring is broken in one direction only, which is exactly the bug that a forward-only test cannot see. The ring invariants check both directions.

5. An Erased std::list Node

// erase_then_deref.cpp - DO NOT COPY. std::list::erase() destroys the node and
// frees its storage, so the iterator that named that node dangles; dereferencing
// it is undefined behaviour and AddressSanitizer reports heap-use-after-free.
// Erase by iterator and do not touch the iterator again; an erase-by-value call
// has no iterator to leak, and a loop that erases as it walks calls
// erase() and takes its return value as the next iterator.
// Build: g++ -std=c++17 -Wall -Wextra -pedantic -g -fsanitize=address pitfalls/erase_then_deref.cpp -o erase_then_deref
#include <iostream>
#include <list>

int main()
{
    std::list<int> values = {10, 20, 30};
    std::list<int>::iterator position = values.begin();
    ++position;   // the node holding 20

    std::cout << "erase_then_deref: iterator into an erased std::list node\n";
    std::cout << "value before erase: " << *position << '\n';

    // The node is destroyed and its storage is freed. position still holds the
    // old address; nothing about it says the node is gone.
    values.erase(position);
    std::cout << "size after erase: " << values.size() << '\n';
    std::cout.flush();

    // AddressSanitizer stops at this read of the freed node.
    std::cout << "value after erase: " << *position << '\n';
    return 0;
}

Output:

AddressSanitizer: heap-use-after-free
READ of size 4 at pitfalls/erase_then_deref.cpp:27
16 bytes inside a 24-byte region freed at pitfalls/erase_then_deref.cpp:22
allocated at pitfalls/erase_then_deref.cpp:13
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/erase_then_deref.cpp:27 in main

Erasing a std::list node invalidates the iterator that pointed at it, and this program dereferences that iterator afterwards. AddressSanitizer reports a 4-byte read inside the freed 24-byte node. The fix is the one the standard container supports: erase returns the iterator to the next node, so reassign it instead of incrementing the old one. Erasing invalidates only the erased iterator, which is why the container makes that return value useful.

Key Takeaways

  • A doubly linked node stores a value and two links. The backward link makes removal of a held node O(1) and reverse traversal possible without reversing the list.
  • One sentinel node closes the list into a ring, so the empty, single-element and boundary cases all become the same four pointer writes and the null checks disappear.
  • Over the same 200,000 operations the sentinel version evaluated 233,456 conditionals against 433,456 for the head/tail version with identical output.
  • Rotation is O(k) pointer work in the ring and O(n) element moves in an array. 10,000 rotations of 100,000 values cost 0.05 ms against 82.76 ms.
  • The O(1) removal needs a node handle. remove(value) still searches, and Python’s deque is not a linked list at all.
  • std::list, Java’s LinkedList and C#’s LinkedList<T> are all doubly linked with node or iterator handles. libstdc++’s std::list uses a header node like the sentinel here, while Java and .NET use null-checked end references.
  • The extra pointer is the price: one pointer of memory per node and extra writes per operation, plus worse cache behavior than a contiguous array.

Frequently Asked Questions

Conclusion

The second pointer is a small change with a large consequence. Removal of a held node becomes two writes, reverse traversal becomes a loop over prev, and the sentinel ring makes the empty, first and last cases disappear from the code. The measured workload evaluated 200,000 fewer conditionals, exactly one per operation, and produced the same output. Rotation shows the circular shape at its best, 0.05 ms against 82.76 ms for an array, because a ring moves pointers while an array moves data.

The trade-off is real and the benchmark states it: a linked list pays for scattered nodes on every walk, and std::deque was six times faster on the sequential sum. Use the list when the workload moves nodes, use an array-based container when it walks them, and use the standard containers’ node handles when you need O(1) removal without writing the ring yourself. The queue article covers the deque, the array-based answer for work at both ends, the types of data structures guide places the list beside the other linear structures, and the data structures hub lists the whole series.

Source Code and Tests

All programs on this page are in the data-structures/doubly-linked-list directory of the five MYCPLUS example repositories:

LanguageRepository directoryBuild status
Cmycplus/c-examples: data-structures/doubly-linked-listC doubly linked list build status
C++mycplus/cpp-examples: data-structures/doubly-linked-listC++ doubly linked list build status
Javamycplus/java-examples: data-structures/doubly-linked-listJava doubly linked list build status
Pythonmycplus/python-examples: data-structures/doubly-linked-listPython doubly linked list build status
C#mycplus/csharp-examples: data-structures/doubly-linked-listC# doubly linked list build status

The C and C++ examples build and test with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

Java runs with javac --release 17 -Xlint:all -Werror -d build src/*.java tests/*.java followed by java -ea -cp build ListTest. Python runs with python -m unittest discover -s tests -v, and C# with dotnet build DoublyLinkedList.slnx -c Release followed by dotnet run --project tests/ListTests -c Release --no-build.

What the builds check. Every demo’s stdout is compared byte for byte with tests/expected/ordered.txt. The tests compare every operation against a list model over 100,000 random operations, check the ring invariants after churn, remove nodes through handles, rotate the list, and build and clear a large list. The C and C++ workflows also run the tests, demo and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer. The builds do not check the timing or branch figures, which belong to one machine and are captured with the article.

What I Verified

The example directories contain the test programs and the captured runs, and the table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11 (MSVC)
Build and tests, C, GCC 13.3Pass (4 of 4 tests)Not applicable
Build and tests, C, Clang 18.1.3Pass (4 of 4 tests)Not applicable
Build and tests, C, MSVC 19.44 /W4 /WXNot applicablePass (4 of 4 tests)
Build and tests, C++, g++ 13.3Pass (3 of 3 tests)Not applicable
Build and tests, C++, clang++ 18.1.3Pass (3 of 3 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (3 of 3 tests)
Java tests (JDK 21 on WSL, JDK 27 on Windows)Pass (tests and the demo diff)Pass (tests and the demo diff)
Python tests (3.12.3 on WSL, 3.14.6 on Windows), ruff and mypy –strictPass (17 tests, ruff and mypy clean)Pass (17 tests, ruff and mypy clean)
.NET build and tests (10.0.115 on WSL, 10.0.404 on Windows)Pass (tests and the demo diff)Pass (tests and the demo diff)
AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ tests, demo and pitfallsPass (C 4 of 4, C++ 3 of 3)Not applicable
Five pitfalls, each caught by the check named in its sectionPass (4 C checks, 1 C++ check)Not applicable
Branch, rotation and standard-library experimentsRun on Ubuntu 24.04, output in the sections aboveNot run

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 locally (the CI matrix covers them), macOS, thread safety, and timings on any other machine.

Scroll to Top