Topic 05 of 14
Linked List Patterns
2 patterns and 10 practice problems, each with a recall tip, a diagram, the theory and a Python template.
01
Linked List - In-place Reversal
5 practice problems
Theory
- Use three pointers: prev, curr, next. Redirect curr.next to prev each step.
- To reverse a sub-list: note the node before and after the sub-list, reverse the middle, reconnect.
- Dummy node simplifies edge cases where head changes.
- Time: O(n), Space: O(1).
Code template
python
def reverse_list(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
def reverse_between(head, left, right):
dummy = ListNode(0, head)
prev = dummy
for _ in range(left - 1):
prev = prev.next
curr = prev.next
for _ in range(right - left):
nxt = curr.next
curr.next = nxt.next
nxt.next = prev.next
prev.next = nxt
return dummy.nextPractice problems · 5
Easy#206
Medium#92
Easy#234
Medium#24
Hard#25
02
Linked List - Merge / Sorted Operations
5 practice problems
Theory
- Use a dummy node and a tail pointer. Compare heads of two lists, link the smaller one.
- For K sorted lists: use a min-heap of (value, list_index) to pick the next node.
- Merge sort on a linked list: find middle (fast/slow), split, recurse, merge.
- Time: O(n) for two lists, O(n log k) for k lists.
Code template
python
def merge_two_lists(l1, l2):
dummy = ListNode(0)
tail = dummy
while l1 and l2:
if l1.val <= l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
tail.next = l1 or l2
return dummy.nextPractice problems · 5
Easy#21
Hard#23
Medium#148
Medium#147
Medium#2
Spotted a mistake on this page?
Wrong formula, broken animation or confusing wording. Tell us and we will fix it.