Problem
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
1 | |
Explanation 1
-
First, create a ListNode to hold the result.
-
While
l1andl2are not null, comparel1andl2’s value and putting the smaller one to the result ListNode. -
We need a pointer pointing to the result node.
Solution 1
1 | |
Explanation 2
- We can compare the
l1andl2’s first node value, ifl1’s node value is smaller, then recusivly comparel1.nextwithl2, vice versa. If one of the ListNode is null, simply return another ListNode.
Solution 2
1 | |