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

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
 
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
    const dummy = new ListNode(0)
    let current = dummy
    while(list1 != null ||  list2 != null ){
        if(list1 && list2) {
            if(list1.val > list2.val){
                current.next = new ListNode(list2.val)
                list2 = list2.next
            }else{
                current.next = new ListNode(list1.val)
                list1 = list1.next
            }
        }else {
            //其中一个为空,另外一个还有节点,需要把另外一个的节点都要遍历完
            const next = list1 == null ? list2 : list1
            current.next = new ListNode(next.val)
             if(list1) list1 =list1.next
            if(list2) list2 = list2.next
        }
        current = current.next
       
    }
 
    return dummy.next
};

上面是自己手写的,有如下问题:空间占用大,可以通过直接修改 next 指针,无需新建;还有就是最后只剩一个链表的时候直接接上来就行

改进,迭代法:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
 
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
    const dummy = new ListNode(0)
    let curr = dummy
    while(list1 != null && list2 != null ){
            if(list1.val> list2.val){
                curr.next = list2
                list2 = list2.next
            }else {
                curr.next = list1
                list1 = list1.next
            }
        curr = curr.next
    }
    curr.next = list1 == null ? list2 : list1
 
    return dummy.next
};

递归法:

function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
    //递归法,主要思想是拆解大问题为小问题:当前节点我该选择哪一个
    if(list1 == null) return list2
    if(list2 == null) return list1
 
    if(list1.val<list2.val) {
        list1.next = mergeTwoLists(list1.next,list2)
        return list1
    }else{
        list2.next = mergeTwoLists(list2.next,list1)
        return list2
    }
};