← Linked Lists

Drill #15 — Merge two sorted lists

Easy Dummy Head Linked Lists

In plain English: Combine two sorted linked lists into one sorted linked list.

A dummy head node eliminates edge cases for the first insertion — you just return dummy.next at the end.

Prompt

Merge two sorted linked lists into one sorted list.

Try to write it from scratch before scrolling down.

Solution

def merge_sorted(a, b):
    dummy = tail = Node(0)  # dummy avoids empty-list edge case
    while a and b:
        if a.data <= b.data:
            tail.next = a; a = a.next
        else:
            tail.next = b; b = b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next

# Test: 1->3->5 + 2->4->6 => 1->2->3->4->5->6
O(n+m) time · O(1) space

Related Micro Drills

← Drill #14 Drill #16 →