Doubly Linked Lists
A doubly linked list is a chain of nodes where each node links to both its successor and its predecessor. The extra prev link costs one pointer per node and buys O(1) deletion of a node you already hold and traversal in both directions.
Nodes With Two Links
A doubly linked list is a linear data structure made of nodes, where each node holds a value and two pointers: next to the node after it and prev to the node before it. The list keeps a head reference and usually a tail reference, so both ends are reachable in O(1).
Because the links go both ways, you can walk the list forward from the head, backward from the tail, or in either direction from any node you hold.
The first node's prev and the last node's next are null (NULL in C, nullptr in C++, None in Python). Those nulls mark the ends, and forgetting to set them is the most common structural bug.
The price is one extra pointer per node, 8 bytes on a 64-bit machine. For a list of small integers the two pointers can take more space than the data.
- Node = value +
next+prev head.prevandtail.nextare null- Like any linked list, reaching position k still takes O(k) steps
Insertion in a Doubly Linked List
X.prev = AX.next = BA.next = XB.prev = X
Putting a new node X between neighbours A and B takes the four writes above, in that order. The first two touch only the new node, so the list is still intact if anything goes wrong before step 3.
The classic bug is changing A.next first. Once A.next = X has run, A.next no longer leads to B, so X.next = A.next makes X point to itself and every node after it is lost: a leak in C and C++, silent data loss elsewhere.
At the head, there is no A: set X.next = head and X.prev = null, then head.prev = X if the list was not empty, then head = X. If the list was empty, tail must also become X. At the tail it is the mirror image, and it is O(1) only because the list keeps a tail reference.
Inserting at position k costs O(k) to walk there; the rewiring itself is always O(1).
- New node's links first, neighbours' links second
- An insert into an empty list sets both
headandtail
Deletion in a Doubly Linked List
Given the node X to remove, two writes unlink it: X.prev.next = X.next and X.next.prev = X.prev. No traversal is needed, so deletion is O(1) once you hold the node.
A singly linked list cannot do this. It must change the predecessor's next, and the only way to find the predecessor is to walk from the head, which is O(n). That difference is the reason the prev pointer exists.
The ends need care because one neighbour may be null. If X.prev is null, X was the head, so set head = X.next. If X.next is null, X was the tail, so set tail = X.prev. Deleting the only node sets both to null.
Forgetting the second write is the bug to watch for. The list then prints correctly from the head, but walking back from the tail reaches the deleted node again. Testing only the forward direction never catches it.
In C and C++, free the node afterwards (free(X), delete X). In Java and Python the garbage collector reclaims it once nothing refers to it, which is why clearing the deleted node's own prev and next is good practice.
| List type | Find predecessor | Rewire | Total |
|---|---|---|---|
| Singly linked | O(n) traversal | O(1) | O(n) |
| Doubly linked | O(1) via prev | O(1) | O(1) |
X.prev.next = X.next;X.next.prev = X.prev- Null
prevmeans X was the head; nullnextmeans it was the tail - Print the list backward as well as forward when testing
Terms, operations, and practical uses
Pointer mechanics
- Previous Pointer (prev)An additional reference in every node that points to the node immediately behind it.
- Bidirectional TraversalThe ability to walk the list backward from tail to head, impossible in a singly linked list.
- O(1) DeletionRemoving a node instantly if you hold a reference to it, by bridging its prev and next nodes together.
Structure management
- Tail PointerA reference to the very last node, allowing O(1) insertions at the end and backward traversal.
- Sentinel NodesUsing both a dummy head and dummy tail to ensure every real node has a non-null prev and next, eliminating edge cases.
- Pointer ReassignmentThe complex process of updating four different pointers to safely insert a node between two others.
Real-world uses
- LRU CacheLeast Recently Used cache. Combines a hash map with a doubly linked list to evict the oldest item in O(1) time.
- Browser HistoryStoring web pages so the user can freely step backward and forward through their visited sites.
- Undo/Redo BuffersAllowing users to traverse backward through their action history, and forward if they redo.
Code in Python, C++ and Java
class Node:
def __init__(self, val):
self.val = val
self.prev = None
self.next = None
# Build 10 <-> 20 <-> 30 <-> 40 <-> 50
head = Node(10)
node = head
for value in (20, 30, 40, 50):
node.next = Node(value)
node.next.prev = node
node = node.next
def delete(node):
# The node itself is enough: prev is right there.
if node.prev:
node.prev.next = node.next
if node.next:
node.next.prev = node.prev
node.prev = node.next = None
target = head.next.next # the node holding 30
delete(target)
forward = []
node = head
while node:
forward.append(node.val)
tail = node
node = node.next
backward = []
node = tail
while node:
backward.append(node.val)
node = node.prev
print(' <-> '.join(map(str, forward)), '(forward)')
print(' <-> '.join(map(str, backward)), '(backward)')#include <iostream>
using namespace std;
struct Node {
int val;
Node* prev;
Node* next;
Node(int x) : val(x), prev(NULL), next(NULL) {}
};
void deleteNode(Node* node) {
if (node->prev) {
node->prev->next = node->next;
}
if (node->next) {
node->next->prev = node->prev;
}
delete node;
}
int main() {
Node* head = new Node(10);
Node* node = head;
int values[] = {20, 30, 40, 50};
for (int i = 0; i < 4; i++) {
node->next = new Node(values[i]);
node->next->prev = node;
node = node->next;
}
Node* tail = node;
Node* target = head->next->next; // the node holding 30
deleteNode(target);
for (Node* p = head; p != NULL; p = p->next) {
cout << p->val;
if (p->next) cout << " <-> ";
}
cout << " (forward)\n";
for (Node* p = tail; p != NULL; p = p->prev) {
cout << p->val;
if (p->prev) cout << " <-> ";
}
cout << " (backward)\n";
}class Main {
static class Node {
int val;
Node prev;
Node next;
Node(int x) { val = x; }
}
static void delete(Node node) {
if (node.prev != null) {
node.prev.next = node.next;
}
if (node.next != null) {
node.next.prev = node.prev;
}
node.prev = null;
node.next = null;
}
public static void main(String[] args) {
Node head = new Node(10);
Node node = head;
int[] values = {20, 30, 40, 50};
for (int i = 0; i < values.length; i++) {
node.next = new Node(values[i]);
node.next.prev = node;
node = node.next;
}
Node tail = node;
Node target = head.next.next; // the node holding 30
delete(target);
StringBuilder forward = new StringBuilder();
for (Node p = head; p != null; p = p.next) {
forward.append(p.val);
if (p.next != null) forward.append(" <-> ");
}
System.out.println(forward + " (forward)");
StringBuilder backward = new StringBuilder();
for (Node p = tail; p != null; p = p.prev) {
backward.append(p.val);
if (p.prev != null) backward.append(" <-> ");
}
System.out.println(backward + " (backward)");
}
}Step through it
Running on 10 ⇄ 20 ⇄ 30 ⇄ 40 ⇄ 50, delete the node holding 30
Sentinel Nodes
The null checks in insert and delete exist only for the ends of the list. A sentinel (dummy) node at each end removes them: the real nodes always sit between a dummy head and a dummy tail, so every real node has a non-null prev and next.
With sentinels, delete is always the same two writes and insert the same four, whether the node is first, last or in the middle. An empty list is just the two sentinels pointing at each other. The cost is two extra nodes per list, which is why most library implementations and LRU cache solutions use them.
- Dummy head and tail hold no data
- Removes every
iffrom insert and delete
Singly vs Doubly Linked List
Choose a doubly linked list when you need to remove nodes you already hold, or to move in both directions. Choose a singly linked list when you only walk forward and memory per node matters, as in a stack or a hash table bucket.
| Singly linked | Doubly linked | |
|---|---|---|
| Pointers per node | 1 (next) | 2 (next, prev) |
| Delete a node you hold | O(n), must find the predecessor | O(1) |
| Insert before a node you hold | O(n) | O(1) |
| Walk backward | Not possible | Yes, from the tail or any node |
| Writes per insert | 2 | 4 |
- Doubly: O(1) delete and backward walks, one more pointer per node
- Singly: smaller and simpler when you only go forward
Applications of Doubly Linked List
LRU cache. A cache that evicts the least recently used entry needs O(1) lookup and O(1) reordering. A hash map from key to node gives the lookup; a doubly linked list ordered by recency gives the reordering. On each access the node is unlinked with its own prev and next and moved to the front; on overflow the node before the tail sentinel is evicted. The LRU Cache problem is exactly this design.
Library containers. Java's LinkedList and LinkedHashMap, C++'s std::list and Python's collections.OrderedDict all keep their order in one. Python's deque is a doubly linked list of fixed-size blocks.
Back and forward navigation. Browser history and undo/redo step backward and forward through the same chain of states. The Linux kernel's list_head, used across the kernel, is a circular doubly linked list. Problems such as Flatten a Multilevel Doubly Linked List practise the pointer handling. For a list whose ends join, see circular linked lists.
- Hash map + doubly linked list = O(1) LRU cache
- Ordered maps and deques in Java, C++ and Python
- Anything that steps both back and forward