Skip to content

Linked List

Reach for it when the problem says

  • Reverse
  • merge
  • find the middle
  • detect a cycle
Solved
0/31Solved
Problems
31Problems
Variants
5Variants

Problems

5 variants

In-place reversal

0 of 7 solved

Merging and combining

0 of 6 solved

Fast and slow pointers

0 of 7 solved

Dummy node and relinking

0 of 8 solved

Design and copying

0 of 3 solved

Pattern guide

Linked list questions show up in almost every interview loop because they test one thing very directly: can you change pointers without losing track of the data. The algorithms are short. The bugs are always the same few, a lost next, a missing dummy node, a null dereference at the end, so the people who do well are the ones who recognise the move early and use a template they trust.

What it is

A linked list is a chain of nodes. Each node holds a value and a next pointer to the node after it, and the last node points to nothing (None in Python, null in TypeScript). You only hold the head. There is no index: to reach the fifth node you walk four next pointers.

That one limitation shapes every technique on this page. You cannot step backwards, you cannot jump to the middle, and you cannot ask for the length without walking. What you can do cheaply is change a pointer: inserting or removing a node anywhere is O(1) once you are standing on the node before it.

Here is the most important move, reversing a list in place. Watch the three pointers. nxt saves the rest of the list before curr.next is overwritten.

Reversing 1 → 2 → 3 → 4 in place
1
0
↑curr
2
1
3
2
4
3
prev = Nonelinks = 1→2→3→4

Start with prev = None and curr on the head. Nothing is reversed yet.

1/5

Every node was visited once and only three variables were used, so this is O(n) time and O(1) space. Most linked list problems are a combination of this and a handful of other moves.

Quick check
In the reversal loop, what goes wrong if you write curr.next = prev before saving curr.next?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat it implies
"middle node", "halfway"Fast and slow pointers: fast moves two, slow moves one.
"cycle", "loop", "never ends"Floyd's cycle detection, and phase two if they want the entry node.
"nth from the end", "kth from the end"Two pointers with a fixed gap of n.
"reverse", "in pairs", "k at a time", "between positions"In-place reversal of all or part of the list.
"palindrome", "twin", "front and back"Find the middle, reverse the back half, compare.
"remove all", "delete", "the head may be removed"A dummy node before the head.
"sorted lists", "merge", "k lists"Merge with a dummy and a tail; a heap when there are k lists.
"in place", "O(1) extra space"No arrays: relink the nodes.
"least recently used", "back and forward"A design problem built on a doubly linked list.
"deep copy", "random pointer"A hash map from original node to copy.

Constraint clues

ConstraintWhat it suggests
0 <= number of nodesThe empty list is a real input. Check head before touching head.next.
Up to 10^4 or 10^5 nodesO(n) is the target; repeatedly walking to the tail is O(n²).
k up to 2 * 10^9Reduce k modulo the length before you walk anything.
"Values may repeat" or small value rangesCompare nodes by identity (is, ===), never by value.
"O(1) average time" per operationA hash map plus a doubly linked list.

Input and output shape clues

ShapeWhat it suggests
You get one head and return a headRelinking. The head may change, so think about a dummy node.
You get two headsWalk them together: merging, adding digits, or finding where they join.
You return a node (not a list)The tests check identity: the middle node, the cycle entry, the intersection.
You return nothingThe change happens in place from the original head.
You get an array where every value is a valid indexIt is secretly a linked list: i points to nums[i].

Looks like it but isn't

  • Two pointers on an array. Converging pointers need to step backwards. On a singly linked list they cannot, so you either reverse half the list or copy it into an array (O(n) space).
  • Stack. A stack reverses order for free, which is why it is tempting for palindromes and reordering. It works, but costs O(n) memory that an in-place reversal avoids. Reach for a stack when you must not modify the input, as in Add Two Numbers II.
  • Graphs. A cycle in a list sounds like graph cycle detection, but each node has exactly one outgoing edge, so Floyd's two pointers replace DFS and a visited set.
  • Heap. A heap only earns its place when you have k sorted lists. For two lists a single comparison is enough.
Quick check
Find the node where two lists join. Your solution compares p.val == q.val. Why is that wrong?
Need a nudge? A hint rules out a wrong answer.

The sub-patterns

Fast and slow pointers

Use it when you need a position you cannot index: the middle, the nth node from the end, or whether the list loops. Two pointers walk at different speeds (one and two steps) or with a fixed gap. The faster one measures the list for you, so you never count the length first.

Middle of 1 → 2 → 3 → 4 → 5
1
0
↑slow↑fast
2
1
3
2
4
3
5
4

Both pointers start on the head.

1/3
Python
class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def build(values): head = None for v in reversed(values): head = ListNode(v, head) return head def middle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow 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 print(middle(build([1, 2, 3, 4, 5])).val) # 3print(middle(build([1, 2, 3, 4])).val) # 3, the second middleprint(has_cycle(build([1, 2, 3]))) # False
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space. Best-known problems: Middle of the Linked List, Linked List Cycle, Linked List Cycle II, Remove Nth Node From End of List, Find the Duplicate Number.

Predict the outputPython

What does this print?

values = [10, 20, 30, 40, 50, 60]
slow = fast = 0
while fast < len(values) - 1:
  slow += 1
  fast = min(fast + 2, len(values))
print(values[slow])
Need a nudge? Hints walk you through it.

In-place reversal

Use it when the answer needs nodes in reverse order: the whole list, a stretch between two positions, groups of k, or the back half so you can compare it with the front (palindromes, twin sums, reorder). The template is always the same three-pointer loop. What changes is where you start and where you stop.

Reorder list = three moves you already know
  1. 1. Find the middlefast and slow pointers split 1 2 3 4 5 into 1 2 3 | 4 5
  2. 2. Reverse the back half4 5 becomes 5 4, in place
  3. 3. Weave the halves1 5 2 4 3

Cut the list after the first half so you have two separate chains.

1/3
Python
class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def build(values): head = None for v in reversed(values): head = ListNode(v, head) return head def to_list(node): out = [] while node: out.append(node.val) node = node.next return out def reverse(head, stop=None): """Reverse nodes from head up to (not including) stop.""" prev, curr = stop, head while curr is not stop: nxt = curr.next curr.next = prev prev, curr = curr, nxt return prev print(to_list(reverse(build([1, 2, 3, 4, 5])))) # [5, 4, 3, 2, 1]
Output
Press Run (⌘ Enter) to see what happens.

Starting prev at stop instead of None is the trick for partial reversals: the reversed piece's new tail is already linked to whatever comes after it, which is exactly what Reverse Nodes in k-Group needs.

Complexity: O(n) time, O(1) space. Best-known problems: Reverse Linked List, Reverse Linked List II, Reverse Nodes in k-Group, Palindrome Linked List, Reorder List.

Dummy node and relinking

Use it whenever the head might change: removing nodes by value, cutting out runs of duplicates, partitioning around a value, rotating, splitting into parts. A dummy (or sentinel) node is a throwaway node placed before the head. Every real node now has a predecessor, so deleting the head is the same code as deleting any other node, and you return dummy.next at the end.

Remove every 6 from 6 → 1 → 6 → 2
D
0
↑curr
6
1
1
2
6
3
2
4

Put a dummy D before the head and start curr on it.

1/4
Python
class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def build(values): head = None for v in reversed(values): head = ListNode(v, head) return head def to_list(node): out = [] while node: out.append(node.val) node = node.next return out def remove_all(head, val): dummy = ListNode(0, head) curr = dummy while curr.next: if curr.next.val == val: curr.next = curr.next.next else: curr = curr.next return dummy.next print(to_list(remove_all(build([6, 1, 6, 2]), 6))) # [1, 2]print(to_list(remove_all(build([6, 6]), 6))) # []
Output
Press Run (⌘ Enter) to see what happens.

Partition List and Odd Even Linked List use two dummies: build two chains as you walk, then join them. Remember to end the second chain with None, or its old next can make a cycle.

Complexity: O(n) time, O(1) space. Best-known problems: Remove Linked List Elements, Remove Duplicates from Sorted List II, Partition List, Odd Even Linked List, Rotate List.

Merging and combining

Use it when you walk two or more lists together: merging sorted lists, adding numbers stored as digits, sorting a list (merge sort is split plus merge). Keep a dummy node and a tail pointer, append one node per step, and attach the leftover at the end. With k lists, a min-heap of the k front nodes picks the next one in O(log k).

Merging 1 → 4 and 2 → 3
1
0
↑a
4
1
|
2
2
3
↑b
3
4
result = D

Two sorted lists, a dummy D, and tail on the dummy.

1/5
Python
import heapq class ListNode: def __init__(self, val=0, next=None): self.val, self.next = val, next def build(values): head = None for v in reversed(values): head = ListNode(v, head) return head def to_list(node): out = [] while node: out.append(node.val) node = node.next return out def merge_two(a, b): dummy = tail = ListNode() while a and b: if a.val <= b.val: tail.next, a = a, a.next else: tail.next, b = b, b.next tail = tail.next tail.next = a or b return dummy.next def merge_k(lists): heap = [(node.val, i, node) for i, node in enumerate(lists) if node] heapq.heapify(heap) dummy = tail = ListNode() while heap: _, i, node = heapq.heappop(heap) tail.next = tail = node if node.next: heapq.heappush(heap, (node.next.val, i, node.next)) return dummy.next print(to_list(merge_two(build([1, 4]), build([2, 3])))) # [1, 2, 3, 4]print(to_list(merge_k([build([1, 5]), build([2, 6]), build([0])]))) # [0, 1, 2, 5, 6]
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n + m) for two lists; O(N log k) for k lists with N nodes in total. Best-known problems: Merge Two Sorted Lists, Merge k Sorted Lists, Add Two Numbers, Sort List.

Design and copying

Use it when the problem asks you to build a structure, not transform a list: an LRU cache, browser history, or a deep copy of a list with extra pointers. The linked list is a building block here. It is usually doubly linked (each node has prev and next), so any node can be unlinked in O(1), and it is often paired with a hash map that finds nodes by key.

LRU cache: two structures working together
  1. Hash map: key → nodefinds any node in O(1)
  2. head ⇄ most recent ⇄ ... ⇄ least recent ⇄ taildoubly linked list ordered by use

get(key) looks the node up in the map. Without the map you would have to walk the list.

1/3
Python
class DNode: def __init__(self, key=0, val=0): self.key, self.val = key, val self.prev = self.next = None class LRUCache: def __init__(self, capacity): self.capacity, self.nodes = capacity, {} self.head, self.tail = DNode(), DNode() self.head.next, self.tail.prev = self.tail, self.head def _unlink(self, node): node.prev.next, node.next.prev = node.next, node.prev def _push_front(self, node): node.prev, node.next = self.head, self.head.next self.head.next.prev = node self.head.next = node def get(self, key): node = self.nodes.get(key) if not node: return -1 self._unlink(node) self._push_front(node) return node.val def put(self, key, val): if key in self.nodes: self._unlink(self.nodes[key]) elif len(self.nodes) == self.capacity: oldest = self.tail.prev self._unlink(oldest) del self.nodes[oldest.key] node = DNode(key, val) self.nodes[key] = node self._push_front(node) c = LRUCache(2)c.put(1, 1); c.put(2, 2); c.get(1); c.put(3, 3)print(c.get(2), c.get(1), c.get(3)) # -1 1 3
Output
Press Run (⌘ Enter) to see what happens.

For copying, the same pairing appears: a map from each original node to its copy lets you wire next and random in a second pass, even when random points ahead to a node you have not copied yet.

Complexity: O(1) per cache operation; O(n) time and space for a deep copy. Best-known problems: LRU Cache, Copy List with Random Pointer, Design Browser History.

A decision checklist

When you read a linked list prompt, ask these in order: do I need a position (middle, end, loop)? Do I need reverse order? Can the head change? Am I walking several lists? Am I building a structure? The first yes usually names the sub-pattern.

Match the pairs0/5 matched

Match each problem to the sub-pattern that cracks it.

Choose an item, then its match on the other side.
Put it in order4 steps

Put the steps of Reorder List (L0, Ln, L1, Ln-1, ...) in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Traps

  • Losing the rest of the list. Save nxt = curr.next before you overwrite curr.next. This is the most common linked list bug.
  • Null dereference at the end. In a fast pointer loop, check fast and fast.next before reading fast.next.next. Check head before reading head.next.
  • Forgetting the head can change. If a node you remove or move might be the head, use a dummy node. Without one you need a separate branch, and that branch is where bugs hide.
  • Moving on after an unlink. When removing nodes, stay on curr after curr.next = curr.next.next; the new curr.next may also need removing.
  • Leaving a stale link. When you build chains by appending (partition, odd/even, split), the last node still points into the old list. Set its next to None, or you create a cycle.
  • Comparing values instead of nodes. For cycles and intersections, the question is about identity. Use is / ===.
  • Off-by-one in the middle. fast = head lands on the second middle for even lengths; fast = head.next lands on the first. Pick on purpose: deleting needs the node before the middle, and merge sort needs the first middle so a two-node list splits evenly.

Always test these inputs: an empty list, one node, two nodes, an odd and an even length, and a case where the head is the node that changes.

Quick check
You partition 1 → 4 → 2 around 3 into a small chain 1 → 2 and a big chain 4, then join them. You forget to set the big tail's next to None. What happens?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Key terms
Dummy node
A throwaway node placed before the head so every real node has a predecessor. Return dummy.next at the end.
Fast and slow pointers
Two pointers moving at one and two steps (or with a fixed gap). They find the middle, the nth node from the end, and cycles in one pass.
Floyd's cycle detection
Fast and slow pointers meet inside a loop; then a pointer from the head and one from the meeting point meet at the loop's entry.
In-place reversal
Flip next pointers with prev, curr and a saved nxt, using O(1) extra space.
Doubly linked list
Each node has prev and next, so any node can be unlinked in O(1). The base of an LRU cache.
Deep copy
A copy made of new nodes whose pointers all point into the copy, never back into the original.