Skip to main content

The Linked List

beginner15 min readLesson 73 of 148

Nodes connected by pointers: O(1) insertion at the head, O(n) to reach the middle.

The node

typedef struct Node {
    int value;
    struct Node *next;    // the tag lets it point at its own type
} Node;

A list is just a Node *head. An empty list is head == NULL. The last node stores next == NULL โ€” that is the end marker.

Building and walking

Node c = {3, NULL};
Node b = {2, &c};
Node a = {1, &b};       // list: 1 -> 2 -> 3
Node *head = &a;

for (Node *it = head; it != NULL; it = it->next) {
    printf("%d ", it->value);
}

The trade-off against arrays

| operation | array | linked list | |-----------|-------|-------------| | access i-th | O(1) | O(n) โ€” must walk | | insert at head | O(n) โ€” shift | O(1) โ€” rewire two pointers | | insert at known node | O(n) | O(1) | | memory | one block | one malloc PER NODE |

The classic bugs

  • losing the rest of the list: rewiring next before saving it
  • walking past the end: testing it->next != NULL when you meant it != NULL
  • memory: heap nodes need one free each โ€” who owns them?

Insert-at-head for practice:

Node *push_front(Node *head, Node *n) {
    n->next = head;
    return n;               // new head
}

Now practice

Linked List WorkbenchWalk, count, and query chains of nodes.4 challenges ยท ยท ~16 min