Linked Lists

A linked list chains nodes together via pointer references. Given a node or its predecessor, pointer links can be spliced locally in O(1), whereas locating a value or indexing by position requires linear traversal.

One-Sentence Definition

A linked list connects nodes via pointer references: once you hold a direct reference to a node (or its predecessor), inserting or splicing links locally takes O(1)O(1), whereas locating a position or indexing by offset requires O(n)O(n) traversal.

Why It Matters

  • Contrasting linked lists against contiguous arrays is the clearest way to understand memory-layout and time-complexity trade-offs in data structures.
  • Doubly linked lists underpin LRU caches, double-ended queues (deque), and OS scheduler run queues.
  • Pointer manipulation problems (in-place reversal, cycle detection, merging sorted lists) build core algorithmic fluency.

Practical Boundaries

Deleting a node from a singly linked list requires a reference to its predecessor node, so holding only the target node reference does not guarantee O(1)O(1) removal. Note also that Python's collections.deque is implemented as a doubly linked list of fixed-size C arrays (blocks) rather than allocating one heap node per element.

How It Works / Diagram

Figure 1
Operation Contiguous Array Linked List
Random access by index O(1)O(1) O(n)O(n)
Insert / delete at head O(n)O(n) O(1)O(1)
Insert after a known node O(n)O(n) O(1)O(1)
CPU cache locality High (contiguous memory) Low (scattered heap nodes)

CPython's collections.deque uses a doubly linked list of fixed-size pointer blocks, delivering O(1)O(1) append and pop at both ends: CPython C source https://github.com/python/cpython/blob/main/Modules/_collectionsmodule.c ; documentation https://docs.python.org/3/library/collections.html#collections.deque .

Fast/slow pointer cycle detection (Floyd's Tortoise and Hare algorithm): the slow pointer advances 1 step per iteration while the fast pointer advances 2 steps; if a cycle exists, the two pointers are guaranteed to meet inside the loop.

Runnable Example

Implementing a singly linked list from scratch (head insertion, linear search, in-place reversal, and Floyd cycle detection) and benchmarking head insertion/deletion on list vs. collections.deque (verified on Python 3.15.0):

# File: examples/09_linked_list.py
# Linked list: nodes connected by pointers; O(1) head insert, O(n) positional lookup
from dataclasses import dataclass
from typing import Optional

@dataclass
class Node:
    val: int
    next: Optional["Node"] = None

class LinkedList:
    def __init__(self): self.head = None; self.size = 0
    def push_front(self, v):                 # O(1)
        self.head = Node(v, self.head); self.size += 1
    def find(self, v):                       # O(n)
        cur, steps = self.head, 0
        while cur:
            steps += 1
            if cur.val == v: return steps
            cur = cur.next
        return None
    def reverse(self):                       # Classic interview operation: in-place reversal
        prev, cur = None, self.head
        while cur:
            cur.next, prev, cur = prev, cur, cur.next
        self.head = prev
    def __iter__(self):
        cur = self.head
        while cur: yield cur.val; cur = cur.next

ll = LinkedList()
for v in [3, 2, 1]: ll.push_front(v)
print("Linked list:", " -> ".join(map(str, ll)))
print("Searching for 3 took", ll.find(3), "steps")
ll.reverse(); print("After reverse:", " -> ".join(map(str, ll)))

# Fast/slow pointer cycle detection
def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast: return True
    return False
a, b, c = Node(1), Node(2), Node(3); a.next, b.next, c.next = b, c, a
print("Cyclic list has cycle:", has_cycle(a), "| Standard list has cycle:", has_cycle(ll.head))

# Standard library doubly linked block list: collections.deque
from collections import deque
from timeit import timeit
lst, dq = list(range(100_000)), deque(range(100_000))
print(f"1000 head insert+pop ops: list {timeit(lambda: lst.insert(0,1) or lst.pop(0), number=1000)*1000:.1f} ms"
      f" | deque {timeit(lambda: dq.appendleft(1) or dq.popleft(), number=1000)*1000:.2f} ms")

Captured output:

Linked list: 1 -> 2 -> 3
Searching for 3 took 3 steps
After reverse: 3 -> 2 -> 1
Cyclic list has cycle: True | Standard list has cycle: False
1000 head insert+pop ops: list 34.2 ms | deque 0.06 ms

Notice the final benchmark line: 1,000 head insert/pop cycles take `34.2 ms` on a 100K-element list (because every call shifts 100,000 pointers in memory) versus `0.06 ms` on deque.

Common Pitfalls

  • "Linked list insertion is always O(1)O(1)": Only pointer splicing is O(1)O(1) once you already have the target node; walking from the head to find the insertion point still takes O(n)O(n).
  • Rolling a custom pure-Python Node class for production speed: Every Python object carries substantial heap header and pointer indirection overhead; use built-in list or collections.deque in production code.
  • Overwriting cur.next during reversal before saving the successor: Always stash nxt = cur.next (or use tuple unpacking) before redirecting pointers.
  • Forgetting edge cases such as empty lists (head is None) or single-node lists.

Connection to AI Development

  • LRU caching: Combining a hash map with a doubly linked list gives O(1)O(1) lookup and O(1)O(1) recency updates—the exact architecture inside Python's functools.lru_cache: https://github.com/python/cpython/blob/main/Lib/functools.py
  • Non-contiguous KV Cache block management: vLLM's PagedAttention partitions KV caches into fixed-size blocks linked via a block table rather than requiring contiguous VRAM allocations: https://arxiv.org/abs/2309.06180
  • Sliding-window chat history buffers: Maintaining a bounded conversation window or recent telemetry ring buffer cleanly with deque(maxlen=K).

Further Reading

Concept Check

If you are given only the target value to delete from a singly linked list, can the deletion be performed in O(1)O(1) time?

Reference answer: No—locating the node and its predecessor from the head requires O(n)O(n) traversal in the general case.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 09_linked_list.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram