Merge Two Sorted Lists - Problem
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Input & Output
Example 1 — Basic Merge
$
Input:
list1 = [1,2,4], list2 = [1,3,4]
›
Output:
[1,1,2,3,4,4]
💡 Note:
Merge by comparison: 1≤1 (choose list1), 2<3 (choose list1), 3<4 (choose list2), 4≤4 (choose list1), then 4 from list2
Example 2 — One Empty List
$
Input:
list1 = [], list2 = [0]
›
Output:
[0]
💡 Note:
When one list is empty, return the other list directly
Example 3 — Both Empty
$
Input:
list1 = [], list2 = []
›
Output:
[]
💡 Note:
When both lists are empty, return empty list
Constraints
- The number of nodes in both lists is in the range [0, 50].
- -100 ≤ Node.val ≤ 100
- Both list1 and list2 are sorted in non-decreasing order.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two sorted linked lists: [1,2,4] and [1,3,4]
2
Process
Compare nodes and choose smaller values
3
Output
Single merged sorted list: [1,1,2,3,4,4]
Key Takeaway
🎯 Key Insight: Use two pointers to compare current nodes and build merged list in one pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code