A linked list stores a sequence as a chain of nodes, each holding a value and a pointer to the next node. Because nodes can live anywhere in memory, inserting or removing at a known position is O(1) with no shifting, but reaching the k-th element means walking k links. Linked lists are the classic training ground for pointer manipulation, and they power LRU caches, free lists, adjacency lists and the internals of many queues.
Think of it like
A scavenger hunt
Each clue tells you where the next clue is hidden. You cannot jump to clue 7; you must follow clues 1 through 6. But adding a new stop to the hunt is easy: write a new clue, point it at the old next location, and change one earlier clue to point at the new one. Nothing else in the hunt has to move.
How it works
Each node is a small object with a val and a next reference. The list itself only needs a reference to the first node, the head. The last node's next is null, which marks the end. Many implementations also keep a tail reference and a size counter.
head
|
v
[3 | *]--->[7 | *]--->[1 | null]
^
tail- Node
- A value plus one or more links (
next, andprevin a doubly linked list). - Head
- The first node. Losing the head reference loses the whole list.
- Tail
- The last node. Keeping a reference makes appends O(1).
- Sentinel (dummy) node
- A placeholder node that is never removed, used to eliminate special cases at the ends.
Singly, doubly and circular
Singly linked
- Each node has
nextonly - Least memory per node
- Traverse forward only
- Deleting a node needs its predecessor
Doubly linked
- Each node has
prevandnext - Traverse in both directions
- Delete any node you hold in O(1)
- Used by
LinkedList(Java),std::list, LRU caches
Circular
- The tail links back to the head
- No
nullend; stop when you return to the start - Natural for round-robin scheduling and ring buffers
- A single tail reference reaches both ends
Operations and their costs
| Operation | Singly | Doubly | Why |
|---|---|---|---|
| Access k-th element | O(k) | O(k) | Must walk from the head (or tail) |
| Search by value | O(n) | O(n) | Linear scan |
| Insert at head | O(1) | O(1) | Rewire the head reference |
| Insert at tail | O(1) with tail pointer | O(1) | Otherwise O(n) to find the end |
| Insert after a node you hold | O(1) | O(1) | Change two or four links |
| Delete head | O(1) | O(1) | |
| Delete tail | O(n) | O(1) | Singly needs the second-to-last node |
| Delete a node you hold | O(n) | O(1) | Singly must find the predecessor |
- 1
Create the node
node = Node(val). - 2
Point it forward
node.next = prev.next. The new node now holds on to the rest of the list. - 3
Redirect the predecessor
prev.next = node. The chain now passes through the new node. - 4
Fix bookkeeping
If
prevwas the tail, the new node becomes the tail. Increment the size.
Dummy and sentinel nodes
Many list bugs come from special cases: the list is empty, or the node to remove is the head. A dummy node placed before the head gives every real node a predecessor, so one code path handles everything. At the end you return dummy.next as the new head.
def remove_elements(head, val):
dummy = ListNode(0, head) # every real node now has a predecessor
prev = dummy
while prev.next:
if prev.next.val == val:
prev.next = prev.next.next # unlink; prev stays put
else:
prev = prev.next
return dummy.next # the head may have changedDoubly linked lists often use a circular sentinel: a single node whose next is the first element and whose prev is the last. An empty list is a sentinel pointing to itself, and insertions never need null checks. This is the layout used by LRU & LFU Cache implementations and by the Linux kernel's list_head.
Reversing a linked list
Reversal is the most common linked-list interview question. Walk the list once, flipping each next pointer to point backward. You need three references: the previous node, the current node and the saved next node.
| Step | prev | cur | List state |
|---|---|---|---|
| Start | null | 1 | 1 → 2 → 3 → null |
| Flip 1 | 1 | 2 | null ← 1 2 → 3 → null |
| Flip 2 | 2 | 3 | null ← 1 ← 2 3 → null |
| Flip 3 | 3 | null | null ← 1 ← 2 ← 3 |
| Done | Return prev (3) as the new head |
next = cur.next, set cur.next = prev, then advance prev = cur and cur = next.The recursive version reverses the rest of the list first, then hooks the current node onto the end: head.next.next = head; head.next = None. It is elegant but uses O(n) stack space and can overflow on long lists (see Recursion), so the iterative O(1)-space version is preferred.
Merging two sorted lists
Keep a dummy head and a tail pointer. Repeatedly attach the smaller of the two current nodes and advance in that list. When one list runs out, attach the remainder of the other in one step. This takes O(n + m) time and O(1) extra space because nodes are relinked, not copied, and it is the merge step of Merge Sort on linked lists.
Finding the middle
Move a slow pointer one step and a fast pointer two steps at a time. When fast reaches the end, slow is at the middle, all in a single pass. The same idea detects cycles (Floyd's algorithm): if there is a loop, the fast pointer eventually laps the slow one. See Fast & Slow Pointers.
Arrays vs linked lists
| Aspect | Dynamic array | Linked list |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert / delete at the front | O(n) | O(1) |
| Insert / delete at a known position | O(n) (shifting) | O(1) (relinking) |
| Append at the end | O(1) amortized | O(1) with a tail pointer |
| Memory per element | Just the value (plus spare capacity) | Value plus 1 or 2 pointers plus allocator overhead |
| Cache behavior | Excellent: contiguous | Poor: nodes scattered across the heap |
| Binary search | Yes | No (no random access) |
Complexity
| Operation | Singly | Doubly | Notes |
|---|---|---|---|
| Access / search | O(n) | O(n) | No random access |
| Insert at head | O(1) | O(1) | |
| Insert at tail | O(1) | O(1) | Singly needs a tail pointer |
| Delete a node you hold | O(n) | O(1) | Singly must find the predecessor |
| Reverse | O(n) | O(n) | O(1) extra space iteratively |
| Merge two sorted lists | O(n + m) | O(n + m) | Relinks nodes, O(1) extra space |
| Find the middle | O(n) | O(n) | Fast and slow pointers, one pass |
Space is O(n) for n nodes, plus one pointer per node (singly) or two (doubly).
Implementation
O(1) push at both ends and pop from the front, O(1) insert after a known node, and removal by value using a dummy node.
from typing import Optional
class Node:
def __init__(self, val: int, next: "Optional[Node]" = None) -> None:
self.val = val
self.next = next
class SinglyLinkedList:
def __init__(self) -> None:
self.head: Optional[Node] = None
self.tail: Optional[Node] = None
self.size = 0
def push_front(self, val: int) -> None: # O(1)
self.head = Node(val, self.head)
if self.tail is None:
self.tail = self.head
self.size += 1
def push_back(self, val: int) -> None: # O(1) thanks to the tail pointer
node = Node(val)
if self.tail is None:
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
self.size += 1
def pop_front(self) -> int: # O(1)
if self.head is None:
raise IndexError("pop from empty list")
node = self.head
self.head = node.next
if self.head is None:
self.tail = None
self.size -= 1
return node.val
def find(self, val: int) -> Optional[Node]: # O(n)
cur = self.head
while cur is not None and cur.val != val:
cur = cur.next
return cur
def insert_after(self, node: Node, val: int) -> None: # O(1)
node.next = Node(val, node.next) # link forward first
if node is self.tail:
self.tail = node.next
self.size += 1
def remove(self, val: int) -> bool: # O(n), first occurrence
dummy = Node(0, self.head) # sentinel: no head special case
prev = dummy
while prev.next is not None and prev.next.val != val:
prev = prev.next
if prev.next is None:
return False
if prev.next is self.tail:
self.tail = None if prev is dummy else prev
prev.next = prev.next.next
self.head = dummy.next
self.size -= 1
return True
def to_list(self) -> list[int]:
out, cur = [], self.head
while cur is not None:
out.append(cur.val)
cur = cur.next
return out
lst = SinglyLinkedList()
for v in (1, 2, 3):
lst.push_back(v)
lst.push_front(0)
node = lst.find(2)
if node is not None:
lst.insert_after(node, 9)
lst.remove(0)
print(lst.pop_front(), lst.to_list()) # 1 [2, 9, 3]Key takeaways
- A linked list is a chain of nodes; access is O(n), but inserting or deleting at a node you already hold is O(1).
- Doubly linked lists can delete any held node in O(1); singly linked lists need the predecessor.
- A dummy (sentinel) node removes the special cases for an empty list and for changes at the head.
- Reverse iteratively with prev, cur and next in O(1) space; merge sorted lists with a dummy head and tail pointer.
- Fast and slow pointers find the middle and detect cycles in one pass.
- Arrays usually win in practice thanks to cache locality; choose lists for O(1) splicing at known nodes.
Common pitfalls
- Redirecting
prev.nextbefore linking the new node forward, which orphans the rest of the list. - Dereferencing
node.next.nextwithout checking thatnode.nextexists. - Forgetting to update the tail pointer when removing or inserting at the end.
- Using recursive reversal on very long lists and overflowing the call stack.
- Losing the head reference while traversing; walk with a separate
curvariable.
Interview tips
- Draw three or four nodes and update arrows step by step before writing code.
- Reach for a dummy head whenever the head can change: removal, merging, partitioning.
- Mention fast and slow pointers for middle, cycle and "k-th from the end" questions.
- Know the trade-offs against arrays, including cache locality, when asked which to use.
Real-world applications
- LRU caches: a hash map plus a doubly linked list for O(1) get and put.
- Memory allocators' free lists and the Linux kernel's intrusive
list_head. - Adjacency lists for sparse graphs and hash table chaining buckets.
- Undo histories, music playlists and round-robin schedulers (circular lists).
Practice problems
Test yourself
In a doubly linked list, how long does it take to delete a node you already hold a reference to?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.