Last Commit: 2024-01-01 16:39:28

views:

Table of Content

21. Merge Two Sorted Lists

source: https://leetcode.com/problems/merge-two-sorted-lists/

Question

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

思路

这题和2题非常的相似,只不过一题是相加,一题是正序合并。原理都很相似,都是对链表的遍历,都要用到dummy head。

额外的注意一点是,undefined || Infinity会被0 || Infinity干扰,所以必须写成三元表达式的形式。

/**
 * 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 n1 = list1;
    let n2 = list2;
    const head = new ListNode();
    let crr = head;
    const getValue = (n) => {
        if (n === undefined || n === null) return Infinity;
        return n.val;
    };
    while (n1 || n2) {
        if (getValue(n1) <= getValue(n2)) {
            crr.next = n1;
            crr = n1;
            n1 = n1.next;
        } else {
            crr.next = n2;
            crr = n2;
            n2 = n2.next;
        }
    }
    return head.next;
};

总结

链表的while遍历方式应用很普遍。