归并
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
思路: 1.首先判断两个节点是否为空,如果一个为空,则返回另一个节点
if(l1 == null) {return l1;}else if(l2 == null) {return l1}
2.比较两个节点的大小,如果一个较小,则将其取出,将他的指向,改为其他节点
else if(l1.val < l2.val) {l1.next = mergeTwoLsts(l1.next, l2);return l1;}else {l2.next = mergeTwoLsts(l1, l2.next);return l2;}
总结
/*** Definition for singly-linked list.* function ListNode(val, next) {* this.val = (val===undefined ? 0 : val)* this.next = (next===undefined ? null : next)* }*//*** @param {ListNode} l1* @param {ListNode} l2* @return {ListNode}*/var mergeTwoLists = function(l1, l2) {if (l1 == null) {return l2;}else if (l2 == null) {return l1;}else if (l1.val < l2.val) {l1.next = mergeTwoLists(l1.next, l2);return l1;}else {l2.next = mergeTwoLists(l1, l2.next);return l2;}};
