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
l1
andl2
are not null, comparel1
andl2
’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
l1
andl2
’s first node value, ifl1
’s node value is smaller, then recusivly comparel1.next
withl2
, vice versa. If one of the ListNode is null, simply return another ListNode.
Solution 2
1 |
|