将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
代码:
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
let mergeTwoLists = function(list1, list2) {
let preHead = new ListNode(0) // 预设一个头的前缀结点,用于拼接两个链表
let node = preHead // 当前生成链表的尾结点
while(list1 !== null && list2 !== null) {
// 每次将list1与list2中小的插入生成链表的尾结点后面,并令操作位置往后移一位
if(list1.val <= list2.val) {
node.next = list1
list1 = list1.node
}
else {
node.next = list2
list2 = list2.next
}
// 尾结点更新
node = node.next
}
// 当某个链表走到最后,其中另一个链表后半部分结点可能未插入,因此,将其直接接到尾结点后面
node.next = list1 === null ? list2 : list1
// 返回预设结点的后一位
return preHead.next
};
let list1 = new ListNode(1, new ListNode(3, new ListNode(4)))
let list2 = new ListNode(2, new ListNode(2, new ListNode(2)))
let res = mergeTwoLists(list1, list2)