Merge Two Sorted Lists
Easy · Linked Lists · Linked List · Recursion · Two Pointers
Problem
Given the heads of two sorted linked lists, splice them into one sorted list and return its head. The result must reuse the existing nodes.
from_list() and to_list() are provided.
Examples
Input: list1 = 1 -> 2 -> 4, list2 = 1 -> 3 -> 4 Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4
Input: list1 = None, list2 = None Output: None
Input: list1 = None, list2 = 0 Output: 0
An empty list merges to the other one.
Constraints
- 0 <= nodes in each list <= 50
- -100 <= Node.val <= 100
- Both lists are sorted ascending
Approaches
- Recursive — time O(n + m), space O(n + m)
Related problems
Start free on Cariara · Coding problems · System design studio