21\. Merge Two Sorted Lists

# 21. Merge Two Sorted Lists (opens new window)

# Description

Difficulty: Easy

Related Topics: Linked List (opens new window), Recursion (opens new window)

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.

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
1
2

Example 2:

Input: list1 = [], list2 = []
Output: []
1
2

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]
1
2

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

# Solution

Language: JavaScript

/**
 * 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}
 * 1.暴力解法
 * 逐一比较最小
 * 模式识别:链表问题考虑哑节点
 * 2.递归
 * 合并(L1,L2)等价于L1->next=合并(L1->next,L2)
 * 模式识别:子问题和原问题具有相同结构,考虑自上而下的递归
 */
var mergeTwoLists = function(list1, list2) {
    const dummy = new ListNode();
    let curr = dummy;
    
    while (list1 && list2) {
        list1.val < list2.val
            ? [curr.next, list1] = [list1, list1.next]
            : [curr.next, list2] = [list2, list2.next];
        
        curr = curr.next;
    }
    
    curr.next = list1 ?? list2;
    
    return dummy.next;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
上次更新: 2022/7/13 上午11:21:17