将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
/**
* 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) return l2
if (!l2) return l1
let res = null
let lastNode = null
while (l1.val !== undefined || l2.val !== undefined) {
let temp
if (l1.val < l2.val || l2.val === undefined) {
temp = new ListNode(l1.val)
if (l1.next) {
l1 = l1.next
} else {
l1.val = undefined
}
} else {
temp = new ListNode(l2.val)
if (l2.next) {
l2 = l2.next
} else {
l2.val = undefined
}
}
// 设置链表初始值
if (!res) {
res = new ListNode(temp.val)
lastNode = res
continue
}
lastNode.next = temp
lastNode = temp
}
return res
};