將兩個(gè)有序鏈表合并為一個(gè)新的有序鏈表并返回模孩。新鏈表是通過拼接給定的兩個(gè)鏈表的所有節(jié)點(diǎn)組成的见坑。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
代碼
/**
* 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) {
//頭節(jié)點(diǎn)
let headNode = {};
//尾節(jié)點(diǎn)
let lastNode = headNode;
while(l1 !== null && l2 !== null){
if( l1.val <= l2.val ){
lastNode.next = l1;
l1 = l1.next;
}else{
lastNode.next = l2;
l2 = l2.next;
}
lastNode = lastNode.next;
}
if(l1 !== null){
lastNode.next = l1;
}else{
lastNode.next = l2;
}
return headNode.next;
};