CC Explainer
C · 4 · Dynamic Memory & Data Structures18 / 35 · 51%

Linked Lists from Scratch

A pointer-chain of dynamically allocated nodes.

shortcuts: ← prev · → next · M mark
1

Node & Head

Each node stores a value and a pointer to the next node.

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

Node *head = NULL;
10•20•30•40•→ NULL
head → 10 → 20 → 30 → 40 → NULL
2

push_front

Allocate, link to old head, update head.

Example
example
void push(Node **head, int v) {
    Node *n = malloc(sizeof *n);
    n->value = v;
    n->next  = *head;
    *head    = n;
}
3

free_all

Walk the chain, free each node — miss one and you leak.

Example
example
void free_all(Node *head) {
    while (head) {
        Node *next = head->next;
        free(head);
        head = next;
    }
}