Show contents
Chapter 1 of 7 · 20 min
Linked lists
By the end of this chapter, you'll be able to
- Define a linked-list node with a self-referencing structure
- Add at the front and go through a list with a pointer
- Remove an item using a pointer to a pointer
- Free every node with no leak and no access to freed memory
Nodes linked by pointers
Each node holds a piece of data and the address of the next node. The last one points to NULL. The list itself is just a pointer to the first node, the head.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char task[40];
struct Node *next;
} Node;
/* Adds at the front: O(1). Returns 0, or -1 if memory runs out. */
int push_front(Node **head, const char *task) {
Node *n = malloc(sizeof *n);
if (n == NULL) return -1;
snprintf(n->task, sizeof n->task, "%s", task);
n->next = *head;
*head = n;
return 0;
}
/* Removes the first node whose task matches. Returns 0 or -1. */
int remove_task(Node **head, const char *task) {
for (Node **p = head; *p != NULL; p = &(*p)->next) {
if (strcmp((*p)->task, task) == 0) {
Node *to_free = *p;
*p = to_free->next;
free(to_free);
return 0;
}
}
return -1;
}
void print_list(const Node *head) {
for (const Node *n = head; n != NULL; n = n->next) {
printf("%s%s", n->task, n->next ? " -> " : "\n");
}
}
void free_list(Node *head) {
while (head != NULL) {
Node *next = head->next;
free(head);
head = next;
}
}
int main(void) {
Node *list = NULL;
push_front(&list, "pay the rent");
push_front(&list, "fix the bike");
push_front(&list, "call Mamadou");
print_list(list);
remove_task(&list, "fix the bike");
print_list(list);
printf("removing a missing task: %d\n", remove_task(&list, "swim"));
free_list(list);
return 0;
}
call Mamadou -> fix the bike -> pay the rent
call Mamadou -> pay the rent
removing a missing task: -1
struct Node *next: a structure can contain a pointer to its own type. That's why we name the structure (struct Node) as well as thetypedef.push_frontreceivesNode **head, the address of the head pointer: it must be able to change it so that it points to the new node.snprintf(n->task, sizeof n->task, "%s", task)copies the string without ever exceeding the field's size, unlikestrcpy.
Removing with a pointer to a pointer
Removing a node means making the link that led to it point to the node after it. That link is either the head, or the next field of the previous node. The pointer to a pointer p refers precisely to "the current link": the same code handles both cases, with no special case for the head.
We free the removed node, kept in to_free. No node is lost, no leak.
Text description of the animation
- List: call Mamadou → fix the bike → pay the rent. We remove "fix the bike".
- p points to the list's head itself.
- It's not the right node: we move on.
- p now points to the first node's next field: it's the link leading to "fix the bike".
- We make this link point to the node after: "fix the bike" is no longer in the chain.
- We free the removed node, kept in to_free. No node is lost, no leak.
List or array?
| Operation | Array | Linked list |
|---|---|---|
| access to the n-th item | O(1) | O(n), you have to go through |
| add or remove at the front | O(n), shifting | O(1) |
| add or remove in the middle (known position) | O(n) | O(1) |
| memory | compact | one extra pointer per item |
In practice, a dynamic array (grown with realloc) is often faster, because its items sit next to each other in memory, which the processor loves. The linked list shines when you insert and remove a lot in the middle, or when items must never change address.
Your turn
Worked exercise
Worked exercise: reversing a list
Write a function Node *reverse(Node *head) that reverses a list's order without allocating any new node, only changing the pointers, and returns the new head. Test it on the list 1 → 2 → 3 → 4, built with a push_front function adapted to integers.
Hint 1
previous (at first NULL), current and next.Hint 2
next = current->next, make current->next point to previous, then move previous and current forward one step.Show the solution and common mistakes
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
int push_front(Node **head, int value) {
Node *n = malloc(sizeof *n);
if (n == NULL) return -1;
n->value = value;
n->next = *head;
*head = n;
return 0;
}
Node *reverse(Node *head) {
Node *previous = NULL;
Node *current = head;
while (current != NULL) {
Node *next = current->next;
current->next = previous;
previous = current;
current = next;
}
return previous;
}
void print_list(const Node *head) {
for (const Node *n = head; n != NULL; n = n->next) {
printf("%d%s", n->value, n->next ? " -> " : "\n");
}
}
int main(void) {
Node *list = NULL;
for (int v = 4; v >= 1; v--) {
if (push_front(&list, v) != 0) return 1;
}
print_list(list);
list = reverse(list);
print_list(list);
while (list != NULL) {
Node *next = list->next;
free(list);
list = next;
}
return 0;
}
1 -> 2 -> 3 -> 4
4 -> 3 -> 2 -> 1
Common mistakes:
- Changing
current->nextbefore storing the old next: the rest of the list is lost, and its nodes can never be freed again (memory leak). - Forgetting to take the return value (
list = reverse(list)):liststill points to the old first node, now the last, and you only see a single item.
Summary
- 1A linked list connects nodes with pointers; the last one points to NULL.
- 2To change the head, a function receives the address of the head pointer (Node **).
- 3A pointer to a pointer refers to "the current link" and simplifies removal.
- 4Adding at the front costs O(1), accessing the n-th item O(n).
- 5To free, read the next one before calling free.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.