Skip to content
systemcoding.dev
Fundamentals

Insert into a linked list without special cases using a pointer to a pointer

Insert into a sorted singly linked list in C with a pointer to a pointer, so the empty list and the new head need no special case. Compiles with GCC 14.2.

2 min read
Summarize in AI

The usual insert has an if for the head: a new smallest value has no predecessor to patch. Walk with a pointer to the link you would overwrite, and the head is just another link. pp starts at the address of head, and each step moves it to the address of the next node's next field.

insert.cc
#include <stdio.h>

struct node { int v; struct node *next; };

static void insert_sorted(struct node **head, struct node *n)
{
    struct node **pp = head;

    while (*pp && (*pp)->v < n->v)
        pp = &(*pp)->next;
    n->next = *pp;
    *pp = n;
}

int main(void)
{
    struct node a = {30}, b = {10}, c = {20};
    struct node *head = NULL;

    insert_sorted(&head, &a);
    insert_sorted(&head, &b);
    insert_sorted(&head, &c);
    for (struct node *p = head; p; p = p->next)
        printf("%d ", p->v);
    putchar('\n');
    return 0;
}
Text
10 20 30

When the loop stops, *pp is the link that points at the first node not smaller than the new one, or the null at the end. Pointing n->next at it and then overwriting the link with n is the whole insert, whether that link was head or some node's next. There is no previous-node variable and no branch.

The cost is that the code reads oddly until you picture the addresses. Keep a comment on pp saying it is the link, not the node. Equal values go after existing ones here because the test is a strict <, which keeps the insert stable.

Taggedc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.