Reading history

Linked List in C: Insert, Delete and Reverse

6 min read 1 views

Build a singly linked list in C: node structs, insert at front and end, delete by value, reverse the list, free memory, and compare it with arrays.

A linked list stores items in separate blocks of memory called nodes. Each node holds a value and a pointer to the next node, so the items form a chain. Unlike an array, a linked list can grow one node at a time and insert at the front instantly, but it cannot jump straight to the tenth item.

In this lesson you will learn

  • How a node is built from a struct and a pointer
  • How to insert at the front and at the end
  • How to delete a value and reverse the list
  • How linked lists compare with arrays
  • How to free every node and avoid memory leaks

The Node: Data Plus a Pointer

Each node is a structure that points to another node of the same type. The list itself is just a pointer to the first node, called the head. The last node points to NULL, which marks the end.

head
 |
 v
[10 | *]-->[20 | *]-->[30 | NULL]

Nodes are created with malloc, so they live on the heap until you free them. If you need a refresher, see dynamic memory allocation.

Building a List: Insert at Front and End

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

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

static Node *new_node(int value) {
    Node *n = malloc(sizeof *n);
    if (!n) { perror("malloc"); exit(1); }
    n->data = value;
    n->next = NULL;
    return n;
}

static void push_front(Node **head, int value) {   /* O(1) */
    Node *n = new_node(value);
    n->next = *head;
    *head = n;
}

static void push_back(Node **head, int value) {    /* O(n) without a tail pointer */
    Node *n = new_node(value);
    if (*head == NULL) { *head = n; return; }
    Node *cur = *head;
    while (cur->next) cur = cur->next;
    cur->next = n;
}

static void print_list(const Node *head) {
    for (const Node *p = head; p; p = p->next) printf("%d -> ", p->data);
    printf("NULL\n");
}

int main(void) {
    Node *head = NULL;
    push_back(&head, 20);
    push_back(&head, 30);
    push_front(&head, 10);
    print_list(head);
    while (head) { Node *next = head->next; free(head); head = next; }
    return 0;
}

Output

10 -> 20 -> 30 -> NULL
  • push_front points the new node at the old head and makes it the new head: O(1), no matter how long the list is.
  • push_back must walk to the last node first: O(n). Keeping a separate tail pointer makes it O(1).
  • Both functions take Node **head (a pointer to the head pointer) so they can change which node is first. See pointer to pointer.
  • The loop at the end of main frees each node. It saves next before calling free, because a freed node must not be read.

Deleting a Value and Reversing the List

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

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

static Node *push_front(Node *head, int v) {
    Node *n = malloc(sizeof *n);
    if (!n) exit(1);
    n->data = v; n->next = head;
    return n;
}

static Node *delete_value(Node *head, int v) {
    Node **link = &head;                  /* points at the pointer to change */
    while (*link && (*link)->data != v) link = &(*link)->next;
    if (*link) { Node *gone = *link; *link = gone->next; free(gone); }
    return head;
}

static Node *reverse(Node *head) {
    Node *prev = NULL;
    while (head) { Node *next = head->next; head->next = prev; prev = head; head = next; }
    return prev;
}

static void show(const char *label, const Node *h) {
    printf("%-10s", label);
    for (; h; h = h->next) printf("%d ", h->data);
    printf("\n");
}

int main(void) {
    Node *list = NULL;
    for (int v = 5; v >= 1; v--) list = push_front(list, v);
    show("start:", list);
    list = delete_value(list, 3);
    show("delete 3:", list);
    list = reverse(list);
    show("reversed:", list);
    while (list) { Node *n = list->next; free(list); list = n; }
    return 0;
}

Output

start:    1 2 3 4 5 
delete 3: 1 2 4 5 
reversed: 5 4 2 1

delete_value walks a pointer-to-pointer called link through the list. When it finds the value, *link = gone->next unhooks the node, whether it is the head or in the middle, with no special case. reverse flips each next pointer in one pass using three pointers: prev, head and next. Both run in O(n) time and O(1) extra memory.

Linked List vs Array

OperationArraySingly linked list
Read the i-th itemO(1)O(n): walk from the head
Insert at the frontO(n): shift everythingO(1)
Insert at the endO(1) if there is roomO(n), or O(1) with a tail pointer
Delete a known nodeO(n): shiftO(1) once you have the previous node
Extra memoryNoneOne pointer per node
Cache friendlinessExcellent: items sit side by sidePoor: nodes are scattered

Use an array when you read by position often. Use a linked list when you insert and delete at the front or in the middle often, as in undo lists, free-memory lists inside an allocator, or the chains inside a hash table.

Pointer Mistakes to Avoid

  1. Losing the head. Walking with head = head->next inside main loses the start of the list. Use a separate pointer such as cur.
  2. Using a node after free. Save next first, then free.
  3. Forgetting the empty-list case. Every function must work when head is NULL.
  4. Passing Node * when the head may change. Pass Node **, or return the new head.
  5. Never freeing the list. Each malloc needs a matching free.

Practice Exercises

Exercise 1. Write a function that returns the number of nodes in a list.

Show answer
int length(const Node *h) {
    int n = 0;
    for (; h; h = h->next) n++;
    return n;
}

Exercise 2. What is the time complexity of finding the middle node with one pass using a slow and a fast pointer?

Show answer

O(n). The fast pointer moves two steps for each step of the slow one; when it reaches the end, the slow pointer is at the middle.

Exercise 3. Why does push_front need Node **head rather than Node *head?

Show answer

It must change the caller’s head pointer. With Node *head it would only change its own local copy.

Frequently Asked Questions

What is a doubly linked list?

Each node also stores a pointer to the previous node. That allows walking backwards and deleting a node in O(1) when you only have a pointer to it, at the cost of one more pointer per node.

Is a linked list faster than an array?

Only for insertions and deletions at known positions. For reading and scanning, arrays are usually much faster because their items sit together in memory.

What is a circular linked list?

The last node points back to the first instead of to NULL. It suits round-robin tasks, such as giving each player a turn in a game.

Summary

  • A linked list is a chain of nodes, each holding data and a pointer to the next node.
  • Insert at the front in O(1); reach the i-th item in O(n).
  • Pass Node ** (or return the new head) when the head can change.
  • Save next before freeing a node, and free every node you allocate.
Lessons are also marked complete when you click Next.

Leave a Reply

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