输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
分析:
- 如果l1 = null,返回l2
- 如果l2 = null,返回l1
- 如果l1 = null && l2 == null,返回null
- 如果l1 l2都不为空,从头开始比较,如果l1.val < l2.val将l1.val添加到新链表中,在将l1.next和l2传进去,将结果传给新链表的next;如果l1.val > l2.val将l2.val添加到新链表中,在将l1和l2.next传进去,将结果传给新链表的next。最后所有的执行完毕后返回新链表。
var mergeTwoLists = function(l1, l2) {
var newNode = new ListNode(null);
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1 == null && l2 == null) return null;
if(l1.val < l2.val){
newNode = l1;
newNode.next = mergeTwoLists(l1.next,l2);
}else{
newNode = l2;
newNode.next = mergeTwoLists(l1,l2.next);
}
return newNode;
};