合并两个有序链表

130 阅读1分钟

题目:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

易忘点const nodeHead = new ListNode(-1)

思路:遍历两个链表比较值,返回链表指向数值小的

var mergeTwoLists = function(list1, list2) {
    const nodeHead = new ListNode(-1)
    let node = nodeHead
    while(list1 != null && list2 != null){
        if(list1.val < list2.val){
            node.next = list1
            list1 = list1.next
        }else{
            node.next = list2
            list2 = list2.next
        }
        node = node.next
    }
    node.next = list1 == null ? list2 : list1
    return nodeHead.next
}