Section 14.6

Linked list

Definition

A linked list is a data structure that stores a sequence of elements in separate records called nodes. Each node holds one element and a reference, or pointer: the memory address of the next node. In a singly linked list each node refers to the next node only; in a doubly linked list each node also refers to the previous one. The order lives in the references, not in where the nodes lie in memory, so inserting or removing a node changes a few references and moves no element.

The idea

An array §14.5 keeps its elements side by side in memory, so the element at any position is found with one address calculation, but every change to the sequence moves elements. Removing the first of 10,000 elements from an array means moving the other 9,999 one place forward. A linked list gives up the side-by-side layout. Each element sits in its own node, wherever memory was free, and each node records where the next node is.

A treasure hunt is a fair picture. Each clue says where the next clue is hidden, so the clues can lie anywhere, and a clue is taken out of the hunt by rewriting the clue before it to point past it. Nothing else moves. The picture also shows the two costs. To reach the fifth clue, a player must read the first four, because no clue says directly where the fifth one is. And a player who already holds the removed clue can still read it and follow it, which is the main hazard of removal in a program as well. The picture stops at one point: a doubly linked list also has clues that point backwards, and every backward clue must stay consistent with the forward clues.

How it works

The parts have names.

A circular list instead links the last node back to the first, so a walk must stop when it returns to its starting node. A sentinel is a dummy node that holds no element and is always present; it gives the first and last real nodes neighbors and so removes the special cases at the ends.

Costs are written in the notation of asymptotic complexity §14.2: O(1)O(1) means a number of steps that does not grow with the length nn of the list, and O(n)O(n) a number that grows at most in proportion to nn. Reaching the node at a given position, or finding the node that holds a given element, means walking from the head: O(n)O(n). Inserting or removing next to a node the program already holds is O(1)O(1), because only the references around that node change. Removal from a singly linked list is the exception: the predecessor’s next must change, and a node does not know its predecessor, so the program must also hold the predecessor or find it by a walk from the head, in O(n)O(n).

Removing a node BB from a doubly linked list takes these steps.

  1. Read the neighbors of BB: let AA be the node that the prev of BB refers to, and CC the node that the next of BB refers to. Either may be absent.

  2. Repair the forward direction. If AA exists, set the next of AA to CC. Otherwise BB was the first node, so set the head to CC.

  3. Repair the backward direction. If CC exists, set the prev of CC to AA. Otherwise BB was the last node, so set the tail to AA.

  4. Update any summary the list keeps, such as a count of its nodes.

  5. Decide when the memory of BB may be reused. Steps 2 and 3 make BB unreachable from the list, which is called unlinking. They do not change any reference to BB that another part of the program already holds, so the memory may be freed only when no such reference is still in use.

With a sentinel, AA and CC always exist, and steps 2 and 3 become two unconditional writes.

When several threads, independent sequences of execution that share memory, use one list, the moment between steps 2 and 3 is a hazard: the two directions disagree, and a thread that walks the list then sees an inconsistent list, a race condition §9.2. A mutex §9.5 (mutual exclusion lock) lets one thread at a time touch the list. Read-copy update (RCU) §9.20 instead lets readers walk only next references, so that the single write of step 2 moves them from the old list to the new one, and the remover frees BB only after a grace period §9.21, a time by which every reader that might hold BB has finished.

Worked example

Take a doubly linked list on a 32-bit microcontroller §6.1, where a reference is a 4-byte address. Each node holds a 4-byte number and two references, so a node takes 4+4+4=124 + 4 + 4 = 12 bytes. Four nodes hold the numbers 10, 20, 30 and 40. They lie at scattered addresses, written in hexadecimal:

node address prev next
A (10) 0x2000 null 0x2410
B (20) 0x2410 0x2000 0x2080
C (30) 0x2080 0x2410 0x2300
D (40) 0x2300 0x2080 null

The head holds 0x2000, the address of node A, and the tail holds 0x2300, the address of node D.

Remove B. Step 1 reads the prev of B, 0x2000, so AA is node A, and the next of B, 0x2080, so CC is node C. Step 2 changes the next of A from 0x2410 to 0x2080. Step 3 changes the prev of C from 0x2410 to 0x2000. A walk forward from the head now visits 10, 30, 40, and a walk backward from the tail visits 40, 30, 10. Exactly two references changed, one in each direction. The references stored in B itself still hold 0x2000 and 0x2080, but nothing in the list leads to B any more. Had A been removed instead, the head would have changed from 0x2000 to 0x2410, because A has no predecessor, and the prev of B would have become null.

Suppose a program performs step 2 and forgets step 3. The forward walk is still correct: 10, 30, 40. The backward walk starts at D, reaches C, reads the prev of C, which still holds 0x2410, and visits B: it reports 40, 30, 20, 10, so the removed element reappears. If the 12 bytes of B have meanwhile been freed and reused for other data, the backward walk reads that data as if it were a node, which is a use-after-free §4.6.

The references also cost memory. The 4 nodes take 4×12=484 \times 12 = 48 bytes to hold 4×4=164 \times 4 = 16 bytes of numbers, so 48−16=3248 - 16 = 32 bytes, two thirds of the total, are references. An array of the same 4 numbers takes 16 bytes.

Stated precisely

Let a doubly linked linear list hold the nodes x1,x2,…,xnx_1, x_2, \dots, x_n in this order, with n≥0n \ge 0. The list is well formed when all four of the following conditions hold.

  1. If n=0n = 0, the head and the tail are null. If n≥1n \ge 1, the head refers to x1x_1 and the tail refers to xnx_n.

  2. For every ii with 1≤i<n1 \le i < n, the next of xix_i refers to xi+1x_{i+1}, and the prev of xi+1x_{i+1} refers to xix_i.

  3. The prev of x1x_1 and the next of xnx_n are null.

  4. The nodes x1,…,xnx_1, \dots, x_n are distinct, so a walk along next from the head reaches null after exactly nn nodes and never visits a node twice.

Condition 2 contains the agreement rule: whenever the next of one node refers to a second node, the prev of the second node refers to the first. Agreement alone does not give conditions 1, 3 or 4; a circular list satisfies the agreement rule and breaks condition 3.

Removing xjx_j, for some jj with 1≤j≤n1 \le j \le n, is correct when afterwards conditions 1 to 4 hold for the shorter sequence x1,…,xj−1,xj+1,…,xnx_1, \dots, x_{j-1}, x_{j+1}, \dots, x_n. That takes exactly two reference writes.

A singly linked list needs only the forward write, plus a write to the tail when j=nj = n and the list keeps a tail.

The two-write rule and its O(1)O(1) cost depend on three assumptions.

  1. The program already holds a reference to xjx_j, and in a singly linked list also to xj−1x_{j-1}. Finding the node by its element costs up to nn comparisons first.

  2. The node xjx_j belongs to this list and has not already been removed.

  3. No other thread reads or changes the list between the first and the last write, or the scheme in use, such as RCU, makes every intermediate state safe to observe.

A separate contract covers memory: the storage of xjx_j may be freed or reused only after every reference to xjx_j held outside the list has been dropped.

Limits and common mistakes

Constant-time removal is the cost after the node has been found. Removing “the node holding 30” first costs an O(n)O(n) search, as in an array.

There is no direct access by position, so binary search, which repeatedly jumps to the middle of a sorted range, does not work on a linked list.

Walks are slower than their step counts suggest. Scattered nodes defeat the processor’s cache, a small fast memory that keeps recently used blocks of neighboring bytes; a walk over an array of the same elements reads consecutive bytes and is usually much faster.

Unlinking is not freeing. The removed node keeps its own next and prev, and any thread, table or iterator (an object that remembers a position in the list) that still holds a reference to the node can keep using it. Freeing the node at that point leaves a dangling pointer §4.1. Reference counting §9.22, read-copy update and quiescent points §14.34 are standard ways to decide when the memory may be reused. Some libraries, such as the list code of the Linux kernel, overwrite a removed node’s references with recognizable invalid addresses, so that later misuse fails visibly instead of silently.

Removing a node twice corrupts the list once it has changed in between. Remove B from A, B, C, then insert a new node E between A and C. B still records A and C as its neighbors, so removing B again sets the next of A to C and the prev of C to A, and E silently disappears from the list.

A shortcut removes a node of a singly linked list without its predecessor by copying in the next node’s element and unlinking the next node instead. It fails for the last node, and it changes what outside references to either node see.

Concurrent removals without a lock lose updates. In the singly linked list A, B, C, D, one thread removes B by setting the next of A to C, while another thread removes C by setting the next of B to D. Both writes succeed, yet the next of A refers to C, so C is still reachable after its removal.

A circular list contains a cycle on purpose, and a linear list must contain none. Code written for one kind loops forever or stops early on the other, and an accidental cycle in a linear list makes every complete walk endless.

Questions answered

What additional references must change when one node is removed?

Removing a node BB from a linked list must change every reference inside the list that points to BB. The next reference of the node before BB must now point to the node after BB. In a doubly linked list, where each node also refers to the node before it, the prev reference of the node after BB must now point to the node before BB. When BB is the first node, the list’s head reference changes instead of a predecessor’s next. When BB is the last node, the list’s tail reference, if the list keeps one, changes instead of a successor’s prev. Any summary the list keeps, such as a node count, changes too. If BB belongs to several lists at once, each list needs its own changes.

References to BB held outside the list, by another thread, an iterator or a lookup table, do not change automatically. The memory of BB may be freed only after all of them are gone; otherwise they become dangling pointers, references to memory that now holds something else. When several threads use the list, the changes must also be protected, for example by a mutex, a lock that lets one thread at a time proceed, so that no thread sees the moment when the forward and backward references disagree.

Related entries: Graph reachability search (§14.18), Quiescent point (§14.34), Concurrency versus parallelism (§9.1), Array (§14.5), Use-after-free (§4.6), Read-copy update (RCU) (§9.20).