Reading history

Linked List in C: Insert, Delete, Search and Reverse

7 min read 0 views

Build a singly linked list in C with structs, pointers and malloc: insert at front and end, traverse, search, delete, reverse and free every node.

An array stores its elements side by side in one block of memory, so its size is fixed when you create it. A linked list stores each element in its own small block, called a node, and every node holds a pointer to the next one. The list can grow and shrink one node at a time, and inserting at the front never moves other elements. Building one in C brings together structures, pointers and dynamic memory, which is why it is a classic exercise.

In this lesson you will learn

  • Defining a self-referential struct node
  • Creating nodes with malloc and checking for failure
  • Inserting at the front and at the end
  • Traversing, searching, deleting and reversing
  • Freeing every node to avoid memory leaks

Building and Traversing a List

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

struct node {
    int value;
    struct node *next;          /* pointer to the following node, or NULL */
};

/* Create a node on the heap */
static struct node *new_node(int value) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    n->value = value;
    n->next = NULL;
    return n;
}

/* Insert at the front: O(1) */
static void push_front(struct node **head, int value) {
    struct node *n = new_node(value);
    n->next = *head;
    *head = n;
}

/* Insert at the end: O(n), walks to the last node */
static void push_back(struct node **head, int value) {
    struct node *n = new_node(value);
    if (*head == NULL) {
        *head = n;
        return;
    }
    struct node *cur = *head;
    while (cur->next != NULL)
        cur = cur->next;
    cur->next = n;
}

static void print_list(const struct node *head) {
    for (const struct node *cur = head; cur != NULL; cur = cur->next)
        printf("%d -> ", cur->value);
    printf("NULL\n");
}

static void free_list(struct node *head) {
    while (head != NULL) {
        struct node *next = head->next;   /* save before freeing */
        free(head);
        head = next;
    }
}

int main(void) {
    struct node *head = NULL;           /* an empty list */
    push_back(&head, 20);
    push_back(&head, 30);
    push_front(&head, 10);
    push_back(&head, 40);
    print_list(head);

    int count = 0, sum = 0;
    for (struct node *cur = head; cur != NULL; cur = cur->next) {
        count++;
        sum += cur->value;
    }
    printf("nodes: %d, sum: %d\n", count, sum);

    free_list(head);
    head = NULL;
    print_list(head);
    return 0;
}

Output

10 -> 20 -> 30 -> 40 -> NULL
nodes: 4, sum: 100
NULL
  • struct node contains a pointer to another struct node. This self-referential structure is what links the nodes together. The last node’s next is NULL.
  • The whole list is reached through one pointer, head. An empty list is simply head = NULL.
  • new_node allocates each node on the heap with malloc(sizeof *n) and stops the program if memory runs out.
  • push_front and push_back take struct node **head, a pointer to a pointer, because they may need to change the caller’s head itself.
  • Inserting at the front is O(1). Inserting at the end walks the whole list, which is O(n); keeping a separate tail pointer makes it O(1) too.
  • free_list saves head->next before freeing the node, because reading a node after free is undefined behaviour.

Searching, Deleting and Reversing

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

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

static void push_front(struct node **head, int value) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) exit(EXIT_FAILURE);
    n->value = value;
    n->next = *head;
    *head = n;
}

static void print_list(const struct node *head) {
    for (; head != NULL; head = head->next)
        printf(head->next ? "%d -> " : "%d\n", head->value);
}

/* Return the first node holding value, or NULL */
static struct node *find(struct node *head, int value) {
    while (head != NULL && head->value != value)
        head = head->next;
    return head;
}

/* Remove the first node holding value; returns 1 if removed */
static int remove_value(struct node **head, int value) {
    struct node **link = head;              /* address of the pointer to fix */
    while (*link != NULL && (*link)->value != value)
        link = &(*link)->next;
    if (*link == NULL)
        return 0;
    struct node *gone = *link;
    *link = gone->next;                     /* bypass the node */
    free(gone);
    return 1;
}

/* Reverse the list in place by turning every arrow around */
static void reverse(struct node **head) {
    struct node *prev = NULL, *cur = *head;
    while (cur != NULL) {
        struct node *next = cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
    }
    *head = prev;
}

int main(void) {
    struct node *head = NULL;
    for (int v = 50; v >= 10; v -= 10)
        push_front(&head, v);
    print_list(head);

    printf("find 30: %s\n", find(head, 30) ? "found" : "missing");
    int r1 = remove_value(&head, 30);
    int r2 = remove_value(&head, 99);
    printf("remove 30: %d, remove 99: %d\n", r1, r2);
    remove_value(&head, 10);                /* removing the head works too */
    print_list(head);

    reverse(&head);
    print_list(head);

    while (head != NULL) {                  /* free everything */
        struct node *next = head->next;
        free(head);
        head = next;
    }
    return 0;
}

Output

10 -> 20 -> 30 -> 40 -> 50
find 30: found
remove 30: 1, remove 99: 0
20 -> 40 -> 50
50 -> 40 -> 20
  • find follows next pointers until it reaches the value or NULL. Searching a linked list is always O(n); there is no direct jump to the middle as in an array.
  • remove_value walks with struct node **link, the address of the pointer that points to the current node. When it finds the value, *link = gone->next skips the node, then free releases it. The same code works for the head and for any other node, with no special case.
  • reverse turns every arrow around with three pointers: prev, cur and next. It runs in O(n) time and uses no extra memory.
  • The printing function uses a different format for the last node, so the line ends cleanly without a trailing arrow.

Linked List vs Array

OperationArraySingly linked list
Access the i-th elementO(1)O(n)
Insert or delete at the frontO(n) (shift elements)O(1)
Insert at the endO(1) if space remainsO(1) with a tail pointer, else O(n)
SizeFixed (or reallocated)Grows one node at a time
Extra memoryNoneOne pointer per node
Cache friendlinessExcellentPoor (nodes are scattered)

A doubly linked list adds a prev pointer to each node, so you can walk backwards and delete a node without searching for its predecessor.

Common Mistakes

  1. Passing head by value to a function that should change it, so the caller’s list never updates.
  2. Using a node after freeing it, for example free(cur); cur = cur->next;.
  3. Forgetting to free the list, which leaks memory in long-running programs.
  4. Not handling the empty list (head == NULL) in every function.

Practice Exercises

Exercise 1. Write int length(const struct node *head) using recursion.

Show answer
int length(const struct node *head) {
    return head == NULL ? 0 : 1 + length(head->next);
}

For very long lists the loop version is safer, because each recursive call uses stack space.

Exercise 2. Find the middle node of a list in one pass.

Show answer
struct node *middle(struct node *head) {
    struct node *slow = head, *fast = head;
    while (fast != NULL && fast->next != NULL) {
        slow = slow->next;          /* one step */
        fast = fast->next->next;    /* two steps */
    }
    return slow;                    /* 30 for 10 -> 20 -> 30 -> 40 -> 50 */
}

When the fast pointer reaches the end, the slow pointer is halfway.

Frequently Asked Questions

Why use struct node ** instead of returning the new head?

Both styles work. Returning the new head (head = push_front(head, 5);) is also common. A double pointer lets a function change the caller’s pointer directly and keeps the return value free for a success flag.

When should I use a linked list instead of an array?

When you insert and delete often at the front or in the middle and rarely need random access. For most other jobs a dynamic array is faster because its elements sit together in memory.

Summary

  • A node holds data and a pointer to the next node; the last pointer is NULL.
  • Allocate nodes with malloc and free every one when finished.
  • Use struct node ** when a function must change the head.
  • Front insertion is O(1); search and access by position are O(n).

Next: Stack and Queue in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *