Given the heads of two sorted linked lists list1 and list2, merge them into a single sorted linked list.
The merged list should be constructed by splicing together the nodes from the input lists - don't create new nodes, just rearrange the existing ones. Return the head of the newly merged linked list.
Example:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
This is a classic linked list problem that tests your understanding of pointer manipulation and merging algorithms. It's the foundation for more complex problems like merging k sorted lists.
Input & Output
Visualization
Time & Space Complexity
Visit each node exactly once where n and m are lengths of the lists
Only uses a constant amount of extra space for pointers
Constraints
- The number of nodes in both lists is in the range [0, 50]
- -100 โค Node.val โค 100
-
Both
list1andlist2are sorted in non-decreasing order