Simple Algorithm
Algorithms & Data Structures · Optimized · 20 min

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 kk-th node from the end with one or two pointers.
  • Build an LRU cache with O(1)O(1) 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:

OperationSingly, head onlySingly, head and tailDoubly, head and tail
insert or delete at the frontO(1)O(1)O(1)O(1)O(1)O(1)
insert at the backO(n)O(n)O(1)O(1)O(1)O(1)
delete at the backO(n)O(n)O(n)O(n): the node before the tail must be foundO(1)O(1)
insert after a node you holdO(1)O(1)O(1)O(1)O(1)O(1)
delete a node you holdO(n)O(n): its predecessor must be foundO(n)O(n)O(1)O(1): prev is right there
reach index ii; find a valueO(i)O(i); O(n)O(n)O(i)O(i); O(n)O(n)O(min⁡(i,n−i))O(\min(i, n - i)); O(n)O(n)
All bounds are worst case. A tail pointer lets a singly linked list append in O(1)O(1), but not remove its last node, because removal must rewrite the pointer into that node.

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:

python
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_back

No 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.

Check your understanding

A singly linked list keeps both a head and a tail pointer. Which operation still costs Θ(n)\Theta(n) in the worst case?

  1. Appending a node at the back
  2. Removing the first node
  3. Removing the last node
  4. 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).

python
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

Θ(n)\Theta(n) time and O(1)O(1) extra space: each node's next is written exactly once. A recursive version is shorter but uses Θ(n)\Theta(n) stack frames, which overflows Python's default limit of 1000 on long lists.

DerivationCorrectness by a loop invariant
  1. prev:vk→⋯→v1→∅curr:vk+1→⋯→vn→∅\texttt{prev}: v_k \to \cdots \to v_1 \to \varnothing \qquad \texttt{curr}: v_{k+1} \to \cdots \to v_n \to \varnothing

    Write the list as v1→v2→⋯→vnv_1 \to v_2 \to \dots \to v_n. Invariant: after kk iterations, prev heads the list vk→vk−1→⋯→v1v_k \to v_{k-1} \to \dots \to v_1 and curr heads the untouched rest vk+1→⋯→vnv_{k+1} \to \dots \to v_n. At the start, k=0k = 0: prev is the empty list and curr is the whole list.

  2. prev:vk+1→vk→⋯→v1→∅curr:vk+2→⋯→vn→∅\texttt{prev}: v_{k+1} \to v_k \to \cdots \to v_1 \to \varnothing \qquad \texttt{curr}: v_{k+2} \to \cdots \to v_n \to \varnothing

    Maintenance: the body saves vk+2v_{k+2}, points vk+1v_{k+1} back at vkv_k, and advances both pointers, so the invariant holds for k+1k + 1. The two lists stay disjoint and together contain every node, so nothing is lost.

  3. k=n  ⟹  prev:vn→vn−1→⋯→v1→∅k = n \;\Longrightarrow\; \texttt{prev}: v_n \to v_{n-1} \to \cdots \to v_1 \to \varnothing

    Termination: each iteration processes one node, so after nn iterations curr is empty and prev heads 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: slow moves 1 node per step and fast moves 2; when fast runs off the end, slow is halfway.
  • kk-th node from the end: start lead kk nodes ahead of trail, then move both until lead reaches the last node.
  • Cycles: with fast and slow pointers, fast either runs off the end (no cycle) or laps slow inside the cycle, in O(n)O(n) steps and O(1)O(1) space. The Optimal lesson Cycle Detection: Floyd & Brent proves this and also finds where the cycle starts.
python
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.next

ListNode(val, next) is a plain node with two fields. Merging relinks nodes and allocates nothing, which makes merge sort a natural stable O(nlog⁡n)O(n \log n) sort for linked lists.

Predict before you look

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 cc supports get(key) and put(key, value), and when it is full, put evicts the least recently used key (LRU). Both operations should cost O(1)O(1), and no single structure manages it:

  • a hash map finds a key in O(1)O(1) 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 O(1)O(1), but cannot find a key without a walk.

Together they can: the map sends each key to its node in the list.

python
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: O(1)O(1) expected time, O(c)O(c) 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 O(1)O(1), 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 O(1)O(1) 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 "O(1)O(1) extra space" on a list; splicing, reordering or merging sequences; recency or eviction order.

Problem (in brief)Key ideaCost
Reverse a list, or only the part between positions ll and rrprev, curr, nxt: one arrow flipped per step; for a part, reconnect its two ends afterwardsO(n)O(n), O(1)O(1) space
Merge two sorted listsa dummy head; splice the smaller headO(n+m)O(n + m), O(1)O(1)
Is a list a palindrome?find the middle, reverse the second half, compare, then reverse it backO(n)O(n), O(1)O(1)
Remove the kk-th node from the endlead runs kk nodes ahead; a dummy head covers removing the first nodeO(n)O(n), O(1)O(1)
Does a list have a cycle, and where does it start?fast and slow pointers, then restart one of them at the headO(n)O(n), O(1)O(1)
A cache that evicts the least recently used keya hash map from key to node, plus a doubly linked list in order of useO(1)O(1) expected per operation
A look-alike that does not fit: "access the ii-th element often", or binary search over positions. A list must walk ii nodes to reach position ii, so binary search on a sorted list costs Θ(n)\Theta(n) per query; use an array. And remember that Python's list is a dynamic array, not a linked list.
Check your understanding

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 O(1)O(1) extra memory. Which approach fits?

  1. Store every visited node in a hash set, and return the first one seen twice
  2. Walk the list counting nodes until you reach null
  3. Run fast and slow pointers until they meet, then restart one at the head and move both one step at a time
  4. 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. O(n)O(n) time and two pointers of memory.

Key takeaways

  • Linked lists trade random access (O(i)O(i) to reach index ii) for O(1)O(1) splicing at nodes you hold; a circular doubly linked list with a sentinel makes every insertion and deletion O(1)O(1), with no special cases.
  • Reverse in place with prev, curr and nxt (invariant: prev heads the reversed prefix, curr the untouched rest); merge with a dummy head; find middles, cycles and the kk-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: O(1)O(1) 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 O(1)O(1) updates.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You hold a pointer pp to a node of a singly linked list, but not the head, and you delete pp's value in O(1)O(1) time by copying the next node's value into pp and unlinking the next node. When does this fail?

  1. When pp is the head
  2. When pp is the last node
  3. When the list contains a cycle
  4. When two nodes hold equal values
Show the answer

B. When pp 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.

Question 2

Why does an O(1)O(1) LRU cache keep its keys in a doubly linked list rather than a singly linked one?

  1. To iterate over the keys in both directions when printing the cache
  2. Because hash maps can only point to doubly linked nodes
  3. To unlink an arbitrary accessed node in O(1)O(1), which requires its predecessor
  4. To halve the memory used per node
Show the answer

C. To unlink an arbitrary accessed node in O(1)O(1), 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, O(c)O(c) for a cache of capacity cc.

Question 3

In the iterative reversal while curr: nxt = curr.next; curr.next = prev; prev, curr = curr, nxt, what holds at the top of every iteration?

  1. prev.next == curr, as in the original list
  2. prev heads the reversal of the nodes already processed, and curr heads the untouched rest
  3. The whole list is still reachable from the original head
  4. curr.next already points to prev
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.

Question 4

Traversing a linked list of 10710^7 nodes at scattered addresses can take hundreds of times longer than scanning an array of 10710^7 elements, although both take Θ(n)\Theta(n) time. Why?

  1. Following a pointer costs O(log⁡n)O(\log n)
  2. 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
  3. The list performs more comparisons per element
  4. 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

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).