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.

Efficient singly linked lists with a tail pointer in C

A singly linked list stores a sequence as a chain of separately allocated nodes. Each node holds a value and a pointer to its successor, while the list keeps a pointer to the first node. Adding a tail pointer gives that structure one extra capability: the list can reach its final node immediately, which is valuable whenever new elements are commonly added at the back.

Without a tail reference, appending requires walking from the head until next is NULL, so the operation costs O(n) even though inserting the new node is easy. With a correctly maintained tail, appending becomes O(1). For queue-like workloads, that difference can dominate runtime because every append otherwise repeats the same traversal. The structure still provides no random access, so a tail pointer is a targeted optimisation rather than a universal upgrade.

Australian developers encounter this pattern in university labs and production code. Sydney and Melbourne host many software teams, while courses in Brisbane, Adelaide and Perth often use GCC or Clang on Linux, macOS or Windows. Australian employers in mining, agriculture, defence and fintech also maintain C components beside higher-level Python services, where reliable queues and buffers matter.

Why the tail pointer matters

Think of the list as two views of the same chain. The head pointer starts traversal, and the tail pointer identifies the endpoint; neither pointer owns a separate copy of a node. Every successful append therefore updates at most two links: the former tail’s next field and the list’s tail field. When the list is empty, both endpoints are null. Preserving these relationships is the central invariant of the implementation.

That model connects to broader topics covered by the open programming articles, including pointers, recursion and complexity analysis. Readers who want a wider vocabulary can use those explanations alongside this implementation. The useful mental shift is to treat head, tail and size as a small control structure wrapped around the node chain.

A tail pointer is most useful for append-heavy workloads such as event logs, work queues and ordered buffers. It is less helpful when the list is short, insertions usually occur at the front, or cache locality dominates allocation cost. A dynamic array may be simpler for random indexing, and a doubly linked list may be justified when removing a known node must be O(1). A tail reference cannot accelerate a search by value or provide direct access to an arbitrary position.

Nodes, endpoints and ownership

The node should contain its payload and one next pointer. Keeping the list length is optional, but it makes emptiness checks and tests clearer. A compact C design uses <stdbool.h> for status returns and <stddef.h> for size_t:

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

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

typedef struct {
    Node *head;
    Node *tail;
    size_t size;
} SinglyList;

An empty list has head == tail == NULL and a size of zero. A non-empty list has non-null endpoints, the tail’s next is NULL, and size equals the number of nodes. The tail must never be freed independently because it refers to a node already owned by the chain. For the same reason, do not copy an initialised list by value after it owns nodes; that would create ambiguous ownership. The size field is metadata rather than part of the chain, but it should still agree with every node.

Initialisation and teardown should establish ownership without relying on a sentinel node. A null head is cheaper than allocating a dummy node, and it makes the empty case visible. Destruction walks the chain once, saving each successor before releasing the current node, then clears every field in the list:

SinglyList singly_list_init(void)
{
    SinglyList list = {NULL, NULL, 0};
    return list;
}

void singly_list_destroy(SinglyList *list)
{
    if (list == NULL) {
        return;
    }

    Node *current = list->head;

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

    list->head = NULL;
    list->tail = NULL;
    list->size = 0;
}

Appending and prepending safely

Appending allocates a node, fills it, and links it after the current tail. Allocation must happen before changing the list so a failed malloc leaves the structure untouched. Prepending reverses the direction and must also handle the empty case by setting both endpoints:

bool singly_list_append(SinglyList *list, int value)
{
    if (list == NULL) {
        return false;
    }

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

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

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

    list->tail = node;
    list->size++;
    return true;
}

bool singly_list_push_front(SinglyList *list, int value)
{
    if (list == NULL) {
        return false;
    }

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

    node->value = value;
    node->next = list->head;
    list->head = node;

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

    list->size++;
    return true;
}

Both operations are O(1) after allocation succeeds, and neither changes the relative order of existing values. The empty-list branch in append is essential because there is no former tail to dereference. In prepend, setting the tail only when the old head was NULL preserves the same endpoint invariant. The append path also demonstrates the tail pointer’s main advantage: it never needs to search for the final node.

The C programming tutorials cover pointers and dynamic allocation, which are the two concepts most likely to cause errors in these functions. Compile with warnings enabled rather than relying on visual inspection of pointer assignments, and remember that a bool result distinguishes success from failure. A failed allocation must never leave a half-linked node in the list.

Removing nodes without breaking the chain

Removal needs the predecessor of the target because changing a node’s next field does not update the pointer that referred to it. Scan with current and previous; when a match appears, reconnect previous, then repair head or tail before freeing the node:

bool singly_list_remove_first(SinglyList *list, int value)
{
    if (list == NULL) {
        return false;
    }

    Node *current = list->head;
    Node *previous = NULL;

    while (current != NULL) {
        if (current->value == value) {
            if (previous == NULL) {
                list->head = current->next;
            } else {
                previous->next = current->next;
            }

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

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

        previous = current;
        current = current->next;
    }

    return false;
}

Deleting the head moves head to its successor, but tail changes only when that head was also the sole node. Deleting the tail moves tail to previous; deleting a middle node changes neither endpoint. The function removes the first match, so a duplicate value requires repeated calls or a separately designed operation.

Search is still O(n), and traversal has the same bound because the list provides no random access. Returning a Node * from a lookup exposes internal storage, so prefer a callback, an index-based accessor or a copy-only interface when callers should not modify links. If callers must remove a node by pointer, a pointer-to-pointer update can remove the special case for the head. Neither approach changes the fundamental linear traversal cost.

A reliable testing and maintenance routine

Testing should follow the ownership model. Start with an empty list, then cover one node, many nodes, removal from the head, removal from the tail, duplicate values and failed allocation. On Linux, Valgrind can reveal leaks and invalid accesses; AddressSanitizer and UndefinedBehaviorSanitizer are also available through common C toolchains. Australian development habits often favour terminal-based builds and quick peer review, while programming meetups around Melbourne and Sydney can provide useful test cases and feedback from other developers.

Privacy needs a place in the design, too. If personal information reaches a list used by an Australian organisation covered by the Privacy Act 1988, the Australian Privacy Principles still govern its handling. A linked list does not reduce compliance duties: personal information should be minimised, access should be secured, and debug builds should not retain identifiers unnecessarily. Used with clear ownership and tested edge cases, the tail-pointer version provides predictable O(1) appends without pretending that every linked-list operation is constant time.