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.
next: the reference in a node to the following node.prev: in a doubly linked list, the reference in a node to the preceding node.The head and the tail: references, kept outside the nodes, to the first and the last node. Some lists keep no tail.
The end marker: a null pointer §4.26, a reference value that refers to no node, stored in the
nextof the last node and theprevof the first.
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: means a number of steps that does not grow with the length of the list, and a number that grows at most in proportion to . Reaching the node at a given position, or finding the node that holds a given element, means walking from the head: . Inserting or removing next to a node the program already holds is , 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 .
Removing a node from a doubly linked list takes these steps.
Read the neighbors of : let be the node that the
prevof refers to, and the node that thenextof refers to. Either may be absent.Repair the forward direction. If exists, set the
nextof to . Otherwise was the first node, so set the head to .Repair the backward direction. If exists, set the
prevof to . Otherwise was the last node, so set the tail to .Update any summary the list keeps, such as a count of its nodes.
Decide when the memory of may be reused. Steps 2 and 3 make unreachable from the list, which is called unlinking. They do not change any reference to 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, and 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 only after a grace period §9.21, a time by which every reader that might hold 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 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 is node A, and the next of B, 0x2080, so 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 bytes to hold bytes of numbers, so 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 in this order, with . The list is well formed when all four of the following conditions hold.
If , the head and the tail are null. If , the head refers to and the tail refers to .
For every with , the
nextof refers to , and theprevof refers to .The
prevof and thenextof are null.The nodes are distinct, so a walk along
nextfrom the head reaches null after exactly 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 , for some with , is correct when afterwards conditions 1 to 4 hold for the shorter sequence . That takes exactly two reference writes.
The forward write sets the
nextof , or the head if , to , or to null if .The backward write sets the
prevof , or the tail if , to , or to null if .
A singly linked list needs only the forward write, plus a write to the tail when and the list keeps a tail.
The two-write rule and its cost depend on three assumptions.
The program already holds a reference to , and in a singly linked list also to . Finding the node by its element costs up to comparisons first.
The node belongs to this list and has not already been removed.
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 may be freed or reused only after every reference to 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 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 from a linked list must change every reference inside the list that points to . The next reference of the node before must now point to the node after . In a doubly linked list, where each node also refers to the node before it, the prev reference of the node after must now point to the node before . When is the first node, the list’s head reference changes instead of a predecessor’s next. When 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 belongs to several lists at once, each list needs its own changes.
References to held outside the list, by another thread, an iterator or a lookup table, do not change automatically. The memory of 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).