Merge Two Sorted Lists

easy

Merge two sorted linked lists into one sorted list

Merge Two Sorted Lists

Key Insight

Dummy head eliminates edge cases; always attach the smaller node

Step 1Setup
List 1: [1,3,5]List 2: [2,4,6]
tail
D
null
List 2
p2
2
4
6
null
New nodes
1
3
5

Two sorted lists and a dummy node. Tail pointer starts at dummy.

1 / 6
Practice the Code

Step-by-Step Walkthrough: Merge Two Sorted Lists

Dummy head eliminates edge cases; always attach the smaller node

  1. Setup

    Two sorted lists and a dummy node. Tail pointer starts at dummy.

  2. Compare 1 vs 2

    1 < 2, attach node 1 to tail. Advance p1 to 3.

  3. Compare 3 vs 2

    2 < 3, attach node 2. Advance p2 to 4.

  4. Compare 3 vs 4

    3 < 4, attach node 3. Advance p1 to 5.

  5. Attach Remaining

    Continue comparing: 4 < 5 → attach 4, then 5 < 6 → attach 5, then attach 6.

  6. Result

    Return dummy.next. Merged list is sorted.