Back to problems Solve on LeetCode → See #876 Middle of Linked List →

Merge Two Sorted Lists

LeetCode 21 • Easy • Linked Lists

Input: list1 = [1, 3, 5], list2 = [2, 4, 6]  →  Output: [1, 2, 3, 4, 5, 6]
Merge two sorted linked lists into one sorted list by splicing nodes together.

TimeO(n+m)visit each node once
SpaceO(1)reuse existing nodes
Comparisons: 0 Merged: 0
List 1 / p1
List 2 / p2
Just merged
Consumed
p1
p2
Merged
Ready
Press Play to watch two sorted lists merge into one, or Step to advance one comparison.
At each step, the smaller head is spliced into the result. list1 nodes are green, list2 nodes are blue.