题目:
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: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
这个题目很容易想到使用递归思想,刚开始我主要没搞明白输入的l1和l2到底是什么,其实可以认为最一开始输入的是头指针。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}if(l2 == null){
return l1;
}
if(l1.val > l2.val){
l2.next = mergeTwoLists(l1,l2.next);
//如果l2的值较小,则返回l2节点,然后l2的next指向谁,就要继续判断l1的当前值小还是l2原始next指向的值小,
重新传入这两个节点进行比较,下面的代码同理。
return l2;
}else{
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}
}
}