21. Merge Two Sorted Lists
BF
实现
遍历两个链表,存进数组,排序,生成新链表
提示I - One Pass
实现
/**
* 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) {
const dummy = new ListNode(0);
let last = dummy;
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
last.next = l1;
l1 = l1.next;
} else {
last.next = l2;
l2 = l2.next;
}
last = last.next;
}
if (l1 === null) last.next = l2;
if (l2 === null) last.next = l1;
return dummy.next;
};