← All topics

Linked Lists

No random access, so the tools are different: dummy head nodes to avoid edge cases, fast/slow pointers to find midpoints or cycles, and careful rewiring of .next pointers without losing track of the rest of the list.

206. Reverse Linked List

Given the head of a singly linked list, reverse it and return the new head.

def reverse_list(head):
    prev = None
    while head:
        nxt = head.next
        head.next = prev
        prev = head
        head = nxt
    return prev

Classic three-pointer shuffle: before overwriting head.next, save it as nxt so the rest of the list isn't lost. prev ends up as the new head once head runs off the end.

21. Merge Two Sorted Lists

Merge two sorted linked lists into one sorted list by splicing their nodes together.

def merge_two_lists(l1, l2):
    dummy = tail = ListNode()
    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

A dummy head sidesteps the 'what's the first node' special case -- just build off of dummy.next and return that at the end. Whichever list has nodes left when the other runs out gets attached directly.

Same topic, no training wheels. Solve these on your own before you check the editorial.