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.next

Practice problems · 5

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.next

Practice problems · 5

Spotted a mistake on this page?

Wrong formula, broken animation or confusing wording. Tell us and we will fix it.