You are given the heads of two linked lists that are each sorted in non-decreasing order. Combine them into a single sorted list.
The merged list should be built by splicing together the existing nodes of the two inputs rather than by allocating new ones. Return the head of the resulting list.
Example 1
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Repeatedly picking the smaller front node from the two lists interleaves them into a single sorted chain.
Example 2
Input: list1 = [], list2 = [0]
Output: [0]
When one list is empty there is nothing to compare, so the answer is simply the other list.
Constraints
The number of nodes in both lists is in the range [0, 50].-100 <= Node.val <= 100Both list1 and list2 are sorted in non-decreasing order.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI