21. 合并两个有序链表

55 阅读1分钟

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

image.png

已知两个链表是升序链表,val逐渐增大,而且根据实例,当val相等时,是不分先后的,所以我们主要是比较两个链表的值的大小。 思路: 1、new head. 2、同步递进两个链表,比较大小 3、将小的设为next(),递进下一步循环 4、当某个链表为Null时,将另外一个链接整个接入next 5、return head;

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    let list = new ListNode(null);
    let head = list;
    while(list1 !== null && list2 !== null){
        if(list1.val < list2.val){
            head.next = list1;
            list1 = list1.next;
        }else{
            head.next = list2;
            list2 = list2.next;
        }
        head = head.next;
    }
    head.next = list1 === null ? list2 : list1;

    return list.next
};