May 05, 2021
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.
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode answer = null;
if (l1 == null) {
answer = l2;
} else if (l2 == null) {
answer = l1;
} else if (l1.val < l2.val) {
answer = l1;
l1.next = mergeTwoLists(l1.next, l2);
} else {
answer = l2;
l2.next = mergeTwoLists(l1, l2.next);
}
return answer;
}
}
Source