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 , whereas locating a position or indexing by offset requires 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 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
| Operation | Contiguous Array | Linked List |
|---|---|---|
| Random access by index | ||
| Insert / delete at head | ||
| Insert after a known node | ||
| 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 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 ": Only pointer splicing is once you already have the target node; walking from the head to find the insertion point still takes .
- Rolling a custom pure-Python
Nodeclass for production speed: Every Python object carries substantial heap header and pointer indirection overhead; use built-inlistorcollections.dequein production code. - Overwriting
cur.nextduring reversal before saving the successor: Always stashnxt = 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 lookup and 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
- Python
collections.dequeDocumentation: https://docs.python.org/3/library/collections.html#collections.deque - Wikipedia — Cycle detection (Floyd's Tortoise and Hare): https://en.wikipedia.org/wiki/Cycle_detection
- Cormen et al., Introduction to Algorithms (CLRS), Chapter 10: Elementary Data Structures.
Concept Check
If you are given only the target value to delete from a singly linked list, can the deletion be performed in time?
Reference answer: No—locating the node and its predecessor from the head requires 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