將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是經過拼接給定的兩個鏈表的全部節點組成的。javascript
示例:java
輸入:1->2->4, 1->3->4 輸出:1->1->2->3->4->4this
答案參考:spa
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */
/** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */
var mergeTwoLists = function(l1, l2) {
if ( l1 == null) return l2;
if ( l2 == null) return l1;
if( l1.val < l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1
}else {
l2.next = mergeTwoLists(l1,l2.next);
return l2
}
};
複製代碼