21. Merge Two Sorted Lists
Last updated
Was this helpful?
Last updated
Was this helpful?
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:
Example 2:
Example 3:
Constraints:
The number of nodes in both lists is in the range [0, 50]
.
-100 <= Node.val <= 100
Both l1
and l2
are sorted in non-decreasing order.
Linked List, Recursion
We initialize a dummy head first and assign a pointer to it. We first enter a loop with the condition that both pointers on l1
and l2
are not null. In the loop, the node with smaller value will be connected to the next of the pointer on the new list. After the loop, we concatenate the non-empty list onto the tail of the new list. Finally, return the next node of the dummy head.
If one of the pointers on certain input list is null, we return the other pointer. If both pointers are not null, we obtain the merge result of the node with larger value and the next of the other node, and assign it to the node with smaller value's next, and return this smaller node.
Time complexity: , n
for the length of the longer list;
Space complexity: , created a new list as the result.