Linked Lists
Nodes and pointers: cheap splicing, no random access.
Deleting the middle element of a million-element array moves half a million elements; unlinking a node from a doubly linked list rewrites two pointers. But first you must find the node, and a list makes you walk to it. Linked lists win exactly when you already hold the place to change, which is why they hide inside LRU caches, operating-system kernels and memory allocators, and why interviewers love their pointer puzzles.
What you’ll learn
- Implement singly and doubly linked lists with head, tail and sentinel nodes, and state the cost of every operation.
- Reverse a list in place, and prove the reversal correct with a loop invariant.
- Merge sorted lists, find the middle, detect a cycle and remove the -th node from the end with one or two pointers.
- Build an LRU cache with expected-time get and put from a hash map and a doubly linked list.
- Recognize linked-list problems, and avoid lost heads, null dereferences and accidental cycles.
Singly, doubly, and the sentinel
A singly linked list node holds a value and a next pointer; a doubly linked list node also holds prev. The list itself keeps a head pointer, often a tail pointer, and a size. What each operation costs depends on which of these exist:
| Operation | Singly, head only | Singly, head and tail | Doubly, head and tail |
|---|---|---|---|
| insert or delete at the front | |||
| insert at the back | |||
| delete at the back | : the node before the tail must be found | ||
| insert after a node you hold | |||
| delete a node you hold | : its predecessor must be found | : prev is right there | |
| reach index ; find a value | ; | ; | ; |
Most linked-list bugs live in special cases: the empty list, the first node, the last node. A sentinel removes them. Make the list circular around one dummy node whose next is the first real node and whose prev is the last; the empty list is the sentinel pointing to itself. Every real node then has a real predecessor and a real successor, and one pair of functions does all the work:
class Node:
__slots__ = ("key", "val", "prev", "next")
def __init__(self, key=None, val=None):
self.key, self.val = key, val
self.prev = self.next = self # a lone node is a circular list of one
def link_after(p, x): # insert node x right after node p: O(1)
x.prev, x.next = p, p.next
p.next.prev = x
p.next = x
def unlink(x): # remove node x from its list: O(1)
x.prev.next = x.next
x.next.prev = x.prev
s = Node() # the sentinel: s.next is first, s.prev is last
link_after(s, Node(val=1)) # push_front
link_after(s.prev, Node(val=2)) # push_backNo if statements: the front, the back, the middle and the empty list all take the same path. The key field is used by the LRU cache later in this lesson.
A singly linked list keeps both a head and a tail pointer. Which operation still costs in the worst case?
- Appending a node at the back
- Removing the first node
- Removing the last node
- Inserting a node after one you hold
Show the answer
C. Removing the last node
Removing the last node means setting the second-to-last node's next to null and moving tail to it, and only a walk from the head can find that node. Appending needs just tail.next = new and tail = new.
Reversing in place, with an invariant
Reversal is the canonical pointer exercise: flip every next arrow without allocating a single node. Three pointers walk down the list: prev (the part already reversed), curr (the next node to flip) and nxt (saved so that the rest of the list is not lost).
def reverse(head):
prev, curr = None, head
while curr:
nxt = curr.next # save the rest of the list
curr.next = prev # flip one arrow
prev, curr = curr, nxt
return prev # the new head time and extra space: each node's next is written exactly once. A recursive version is shorter but uses stack frames, which overflows Python's default limit of 1000 on long lists.
Write the list as . Invariant: after iterations,
prevheads the list andcurrheads the untouched rest . At the start, :previs the empty list andcurris the whole list.Maintenance: the body saves , points back at , and advances both pointers, so the invariant holds for . The two lists stay disjoint and together contain every node, so nothing is lost.
Termination: each iteration processes one node, so after iterations
curris empty andprevheads the complete reversal.
Two pointers on a list
Lists have no indices, so many list algorithms run two pointers that move at different speeds or a fixed distance apart:
- Merge two sorted lists by repeatedly splicing the smaller head onto the result. A dummy head node removes the special case of the first splice.
- Middle:
slowmoves 1 node per step andfastmoves 2; whenfastruns off the end,slowis halfway. - -th node from the end: start
leadnodes ahead oftrail, then move both untilleadreaches the last node. - Cycles: with fast and slow pointers,
fasteither runs off the end (no cycle) or lapsslowinside the cycle, in steps and space. The Optimal lesson Cycle Detection: Floyd & Brent proves this and also finds where the cycle starts.
def merge(a, b): # heads of two sorted lists; O(len(a) + len(b)), O(1) extra
dummy = tail = ListNode()
while a and b:
if a.val <= b.val: # <= takes equal keys from a first: a stable merge
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b # splice the rest in one step
return dummy.next
def remove_kth_from_end(head, k): # 1 <= k <= length
dummy = ListNode(0, head) # the dummy also covers removing the head
lead = trail = dummy
for _ in range(k):
lead = lead.next # lead is k nodes ahead of trail
while lead.next: # stop when lead is on the last node
lead, trail = lead.next, trail.next
trail.next = trail.next.next # trail is just before the k-th node from the end
return dummy.nextListNode(val, next) is a plain node with two fields. Merging relinks nodes and allocates nothing, which makes merge sort a natural stable sort for linked lists.
The same loop, while fast and fast.next: slow, fast = slow.next, fast.next.next, runs on a list of 10 nodes with indices 0 to 9. At which index does slow stop?
Show the answer
5
After 5 steps fast has moved 10 nodes, off the end, and slow is at index 5: the second of the two middles, 4 and 5. Looping while fast.next and fast.next.next instead stops one step earlier, at index 4. Decide which one your problem needs, for instance when splitting a list in half for merge sort.
An LRU cache: a hash map plus a doubly linked list
A cache of capacity supports get(key) and put(key, value), and when it is full, put evicts the least recently used key (LRU). Both operations should cost , and no single structure manages it:
- a hash map finds a key in expected time but knows nothing about recency;
- a doubly linked list kept in order of use, most recent first, moves any node to the front and drops the last one in , but cannot find a key without a walk.
Together they can: the map sends each key to its node in the list.
class LRUCache: # capacity >= 1; uses Node, link_after, unlink
def __init__(self, capacity):
self.cap, self.map, self.s = capacity, {}, Node() # s.next: most recent; s.prev: least
def get(self, key):
x = self.map.get(key)
if x is None:
return None
unlink(x); link_after(self.s, x) # mark as most recently used
return x.val
def put(self, key, val):
x = self.map.get(key)
if x is not None:
unlink(x)
else:
if len(self.map) == self.cap: # full: evict the least recently used
lru = self.s.prev
unlink(lru); del self.map[lru.key]
x = self.map[key] = Node(key)
x.val = val
link_after(self.s, x)Each operation is one dictionary lookup plus a constant number of pointer writes: expected time, space. Tested against collections.OrderedDict, whose move_to_end and popitem(last=False) give the same behavior. Python's own functools.lru_cache keeps a dictionary and a circular doubly linked list, and Java's LinkedHashMap in access order does the same.
Think first Why must the list be doubly linked? And why does each node store its key, when the map already sends keys to nodes?
Moving an accessed node to the front means unlinking it from the middle of the list, which needs its predecessor: prev gives it in , where a singly linked list would need a walk. The key is needed at eviction time: the victim is found at the back of the list, and its key is what must be deleted from the map.
Recognizing it
What lists cost in practice. Each node is a separate allocation carrying one or two pointers (8 to 16 bytes on a 64-bit machine) plus the allocator's bookkeeping, and a traversal chases pointers: when the nodes are scattered, every hop can be a cache miss of about 100 ns, where an array scan streams. So use a dynamic array for sequences you mostly scan or index, and a linked list when you splice at positions you already hold, need node addresses that never move (iterators that survive insertions), or need worst-case updates with no reallocation spikes. Operating-system kernels favor intrusive lists, such as Linux's struct list_head, whose prev and next fields live inside the objects themselves, so linking an object allocates nothing. The XOR-linked list stores prev XOR next in a single field and recovers one neighbor from the other while walking: it saves a pointer per node at the price of baffling debuggers and garbage collectors, a curiosity more than a tool.
The signals in a problem statement: you are handed a head, because the input already is a list; "in place" or " extra space" on a list; splicing, reordering or merging sequences; recency or eviction order.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Reverse a list, or only the part between positions and | prev, curr, nxt: one arrow flipped per step; for a part, reconnect its two ends afterwards | , space |
| Merge two sorted lists | a dummy head; splice the smaller head | , |
| Is a list a palindrome? | find the middle, reverse the second half, compare, then reverse it back | , |
| Remove the -th node from the end | lead runs nodes ahead; a dummy head covers removing the first node | , |
| Does a list have a cycle, and where does it start? | fast and slow pointers, then restart one of them at the head | , |
| A cache that evicts the least recently used key | a hash map from key to node, plus a doubly linked list in order of use | expected per operation |
list is a dynamic array, not a linked list.You receive the head of a singly linked list that may contain a cycle, and you must return the node where the cycle begins using extra memory. Which approach fits?
- Store every visited node in a hash set, and return the first one seen twice
- Walk the list counting nodes until you reach null
- Run fast and slow pointers until they meet, then restart one at the head and move both one step at a time
- Copy the values into an array and sort it to find a repeated value
Show the answer
C. Run fast and slow pointers until they meet, then restart one at the head and move both one step at a time
This is Floyd's algorithm: once the pointers meet inside the cycle, a pointer restarted at the head and one left at the meeting point, both moving one step at a time, meet exactly at the cycle's first node. time and two pointers of memory.
Key takeaways
- Linked lists trade random access ( to reach index ) for splicing at nodes you hold; a circular doubly linked list with a sentinel makes every insertion and deletion , with no special cases.
- Reverse in place with
prev,currandnxt(invariant:prevheads the reversed prefix,currthe untouched rest); merge with a dummy head; find middles, cycles and the -th node from the end with two pointers. - An LRU cache pairs a hash map (key to node) with a doubly linked list in order of use: expected time per get and put, as in Python's
functools.lru_cache. - On real hardware lists lose to arrays at scanning, one cache miss per scattered node, but win at stable node addresses, splicing and worst-case updates.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You hold a pointer to a node of a singly linked list, but not the head, and you delete 's value in time by copying the next node's value into and unlinking the next node. When does this fail?
- When is the head
- When is the last node
- When the list contains a cycle
- When two nodes hold equal values
Show the answer
B. When is the last node
The last node has no successor to copy from, and making its predecessor point to null requires that predecessor. Even when the trick works, it moves values between node objects, so outside references to the copied node go stale.
Why does an LRU cache keep its keys in a doubly linked list rather than a singly linked one?
- To iterate over the keys in both directions when printing the cache
- Because hash maps can only point to doubly linked nodes
- To unlink an arbitrary accessed node in , which requires its predecessor
- To halve the memory used per node
Show the answer
C. To unlink an arbitrary accessed node in , which requires its predecessor
On every hit the accessed node moves to the front, so it must be unlinked from wherever it is. Its prev pointer gives the predecessor whose next must change; a singly linked list would have to walk from the head, for a cache of capacity .
In the iterative reversal while curr: nxt = curr.next; curr.next = prev; prev, curr = curr, nxt, what holds at the top of every iteration?
prev.next == curr, as in the original listprevheads the reversal of the nodes already processed, andcurrheads the untouched rest- The whole list is still reachable from the original head
curr.nextalready points toprev
Show the answer
B. prev heads the reversal of the nodes already processed, and curr heads the untouched rest
That is the loop invariant. It holds at the start (an empty reversed part and a whole untouched list), each iteration moves one node from the front of the rest to the front of the reversed part, and at the end curr is empty, so prev heads the full reversal.
Traversing a linked list of nodes at scattered addresses can take hundreds of times longer than scanning an array of elements, although both take time. Why?
- Following a pointer costs
- Each hop may be a cache miss costing about 100 ns, and since each address comes from the previous load the misses cannot overlap; the array scan streams consecutive memory
- The list performs more comparisons per element
- Linked lists store their elements in the wrong order
Show the answer
B. Each hop may be a cache miss costing about 100 ns, and since each address comes from the previous load the misses cannot overlap; the array scan streams consecutive memory
Asymptotic notation hides the constant, and here the constant is the memory hierarchy. The Optimal lesson The Memory Hierarchy & Locality measures about 106 ns per scattered node, against about a tenth of a nanosecond per array element.
Go deeper
- Cycle Detection: Floyd & Brent · Tortoise and hare, the cycle’s start and length, and Pollard’s rho.
- Skip Lists · Randomized express lanes: expected O(log n) search in a linked list.
- Persistent Data Structures · Keeping every version: path copying, fat nodes and functional lists.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), section 10.2 (linked lists).
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 1.3 (linked lists).
- D. E. Knuth, The Art of Computer Programming, Vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), sections 2.2.3–2.2.5 (linked allocation, circular lists, doubly linked lists).