Reversing & Fast/Slow Pointers
Reverse a linked list (a classic!)
Walk through once, flipping each next pointer backwards:
prev = None, curr = head
while curr:
next = curr.next # 1. remember the rest
curr.next = prev # 2. flip the pointer
prev = curr # 3. move prev forward
curr = next # 4. move curr forward
return prev # the new head
O(n) time, O(1) extra space.
Fast and slow pointers
Move slow one step and fast two steps at a time.
| Problem | Trick |
|---|---|
| Middle of the list | when fast reaches the end, slow is in the middle |
| Cycle detection | if there's a loop, fast eventually meets slow (Floyd's algorithm) |
| Nth node from the end | move one pointer n steps ahead first, then move both |
All run in O(n) time with O(1) memory, with no extra list or set needed.
Merging two sorted lists
Compare the heads and attach the smaller one to a growing result (use a dummy node), then move that list forward. It's the core of merge sort on linked lists.
💡 Draw boxes and arrows on paper. Linked-list bugs are almost always a pointer changed in the wrong order.
Example
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse(head):
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prev
def middle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow.val
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(to_list(reverse(build([1, 2, 3, 4, 5])))) # [5, 4, 3, 2, 1]
print(middle(build([1, 2, 3, 4, 5]))) # 3
looped = build([1, 2, 3])
looped.next.next.next = looped # 3 → back to 1
print(has_cycle(looped), has_cycle(build([1, 2]))) # True False