Doubly linked list
easy 16 minA doubly linked list is a chain of nodes where every node links to both its neighbours, the one before (prev) and the one after (next).
Video lesson · Chapter 1 of 6
The return trip
Doubly linked lists — The missing tram car
1:26Reel
Read caption
Vera unlinks car B from a four-car tram by repairing both directions of the route. Two neighbors, two repairs.
How it works
Step through the idea, or press Play.
Link both ways. Every node stores a value, a next pointer forward and a prev pointer back
Understand it
Start here
What a doubly linked list is
A doubly linked list (DLL) is a singly linked list where every node also remembers the node behind it. Each node holds three things: the data, a next pointer to the node ahead and a prev pointer to the node behind. The list keeps a head pointer to the first node and a tail pointer to the last, and both ends finish at None.
Two links per node
nextlooks ahead,prevlooks back. Every node knows both neighbours.Two entry points
headandtaillet you start at either end without walking.Walk either way
Follow
nextfrom the head, orprevfrom the tail. A singly linked list can only go forward.
class Node: def __init__(self, val): self.val = val self.prev = None # who is behind me? self.next = None # who is ahead of me?a, b = Node(10), Node(20)a.next, b.prev = b, a # link both directionsprint(a.next.val, b.prev.val) # 20 10The picture
Two-way links in one picture
A doubly linked list of 10, 20, 30
The invariant every operation must keep
The API
Core operations
| Operation | What it does | On 10 ⇄ 20 ⇄ 30 ⇄ 40 | Time |
|---|---|---|---|
insert_head(x) | Links a new node before the head and moves head | insert_head(5) gives 5 ⇄ 10 ⇄ 20 ⇄ 30 ⇄ 40 | |
insert_tail(x) | Links a new node after the tail and moves tail | insert_tail(50) gives 10 ⇄ … ⇄ 40 ⇄ 50 | |
delete_head() | Moves head to head.next and clears its prev | returns 10, leaves 20 ⇄ 30 ⇄ 40 | |
delete_tail() | Moves tail to tail.prev and clears its next | returns 40, leaves 10 ⇄ 20 ⇄ 30 | |
delete_at(i) | Walks to index i, then links its neighbours to each other | delete_at(1) removes 20 | walk, unlink |
traverse_forward() | Head to tail along next | 10, 20, 30, 40 | |
traverse_backward() | Tail to head along prev | 40, 30, 20, 10 | |
search(x) | Checks nodes one by one from either end | search(30) returns index 2 |
Notice the split: anything at an end is because a pointer already sits there. Anything that needs a position or a value is because the nodes are scattered in memory and must be reached hop by hop.
Under the hood
Inserting at either end
insert_head(x)
head moves. The empty case must also set tail.insert_tail(x)
class Node: def __init__(self, val): self.val, self.prev, self.next = val, None, Nonedef insert_after(node, val): new = Node(val) new.prev = node # 1. new looks back at node new.next = node.next # 2. new looks ahead at node's old next if node.next: node.next.prev = new # 3. old next looks back at new node.next = new # 4. node looks ahead at new return newa = Node(10); c = Node(30)a.next, c.prev = c, ainsert_after(a, 20)print(a.next.val, c.prev.val) # 20 20Under the hood
Deleting from the ends and the middle
delete_tail(): the O(1) advantage
delete_head() is the same path with head, next and prev swapped.Why the prev pointer matters for the tail
tail.prev directly.Unlinking any node you hold
Both directions
Traversal and search
Forward traversal starts at head and follows next until None. Backward traversal starts at tail and follows prev until None, something a singly linked list can only fake by reversing itself first. Search is a traversal that stops early, and because you can start at either end, reaching index only needs the shorter walk.
Reach index i from the closer end
The closer end halves the walk, but it is still linear
class Node: def __init__(self, val): self.val, self.prev, self.next = val, None, Nonenodes = [Node(v) for v in [10, 20, 30, 40]]for a, b in zip(nodes, nodes[1:]): a.next, b.prev = b, ahead, tail = nodes[0], nodes[-1]forward, cur = [], headwhile cur: forward.append(cur.val) cur = cur.nextbackward, cur = [], tailwhile cur: backward.append(cur.val) cur = cur.prevprint(forward) # [10, 20, 30, 40]print(backward) # [40, 30, 20, 10]Complexity
What each operation costs
| Operation | Time | Space | Why |
|---|---|---|---|
| Insert or delete at head | The head pointer is already there | ||
| Insert or delete at tail | The tail pointer is there, and tail.prev gives the new tail | ||
| Unlink a node you hold | Both neighbours are one hop away | ||
| Insert or delete at index | Walking to the index dominates; the splice itself is | ||
| Access by index | At most about hops from the closer end | ||
| Search by value | Nodes are checked one by one | ||
| Traverse either way | Visits every node once | ||
| The list itself | Each node stores a value and two pointers |
The memory price of the prev pointer
Comparison
Doubly vs singly vs array
| Dynamic array | Singly linked (head + tail) | Doubly linked | |
|---|---|---|---|
| Access by index | , from the closer end | ||
| Insert at head | , shifts everything | ||
| Insert at tail | amortised | with a tail pointer | |
| Delete head | |||
| Delete tail | |||
| Delete a node you hold | , shifts | , must find the previous node | |
| Walk backward | Yes | No | Yes |
| Memory per item | Value only | Value + 1 pointer | Value + 2 pointers |
| Cache locality | Excellent | Poor | Poor |
| Code complexity | Simplest | Simple | More edge cases |
Use a doubly linked list when
- You need insert and delete at both ends.
- You move backward as well as forward: back and forward, previous and next.
- You must remove a node you already hold in , as in an LRU cache.
- You build a deque or an ordered map from scratch.
Do not use one when
- You only ever walk forward: a singly linked list is lighter.
- Memory is tight: one pointer per node is cheaper.
- You need random access by index: use an array.
- Scan speed and cache locality matter most: use an array.
Implementation
Sentinels and edge cases
Empty list
Check
head is Nonefirst. Inserting into an empty list sets bothheadandtail.Single node
head is tail. Deleting it clears both pointers.Dangling pointers
Set a removed node's
prevandnexttoNoneso nothing still reaches it.Sentinel nodes
A dummy head and a dummy tail that never hold data. Every real node sits between two nodes, so the special cases disappear.
class Node: def __init__(self, val=None): self.val, self.prev, self.next = val, None, Noneclass SentinelList: def __init__(self): self.front, self.back = Node(), Node() # dummies, never removed self.front.next, self.back.prev = self.back, self.front def _insert_between(self, val, a, b): node = Node(val) node.prev, node.next = a, b a.next = b.prev = node return node def push_front(self, val): return self._insert_between(val, self.front, self.front.next) def push_back(self, val): return self._insert_between(val, self.back.prev, self.back) def remove(self, node): node.prev.next, node.next.prev = node.next, node.prev node.prev = node.next = None return node.val def items(self): out, cur = [], self.front.next while cur is not self.back: out.append(cur.val) cur = cur.next return outlst = SentinelList()lst.push_back(20); lst.push_back(30); n = lst.push_front(10)lst.remove(n)print(lst.items()) # [20, 30]In the wild
Where doubly linked lists run
Browser history
Each page links to the one before (Back) and the one after (Forward).
Music playlists
Previous and Next follow
prevandnextfrom the song now playing.Undo and redo
Each action is a node. Undo steps back along
prev, redo steps forward alongnext.LRU caches
Databases, browsers and CDNs evict the least recently used entry with a hash map plus a doubly linked list.
Window switching
Alt+Tab cycles through open windows in most-recently-used order.
Deques
Python's
collections.dequeis a doubly linked list of blocks: at both ends.
LRU cache: hash map plus doubly linked list
Pattern spotting
Spotting a doubly linked list problem
Should I use a doubly linked list?
LRU cache
Hash map from key to node, list ordered by recency. get and put.
Design browser history
Visit inserts after the current page and drops the forward pages; back and forward walk the links.
Flatten a multilevel list
Nodes also have a child pointer; splice each child list in between a node and its next.
BST to sorted list
An in-order walk relinks left and right as prev and next.
Deque and All O(1)
Double-ended queues, and count buckets kept in order for increment, decrement, min and max.
Related structures: a circular doubly linked list joins tail.next to head and head.prev to tail, so traversal stops when you return to the start rather than at None. A deque, the double-ended cousin of the queue, is the abstract type a doubly linked list implements naturally. A skip list stacks several linked levels to search in expected time.
Recap
Key takeaways
Key points
- Each node stores a value,
nextandprev; the list keepsheadandtail, and both ends stop atNone. - Insert and delete at either end are . Deleting the tail is here and in a singly linked list.
- Unlinking a node you hold is ; finding a position or value is , at most about hops from the closer end.
- The price is one extra pointer per node and more edge cases; space is still .
- Link the new node first, move
headortaillast, and clear both pointers when the last node goes. - Sentinel nodes remove the empty and end special cases.
- LRU cache = hash map + doubly linked list. Browser history, playlists and undo and redo all walk both ways.