[LeetCode] 21. Merge Two Sorted Lists

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

Merge the two lists into 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:
Example 1
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

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

Example 3:
Input: list1 = [], list2 = [0]
Output: [0]

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.

合并两个有序链表。

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

思路

思路是用一个 dummy node 去遍历两个链表,对于来自两个链表上的 node,谁的 val 小谁就在前。直接上代码。

这题的 followup 会是 merge K 个链表,参见 23 题。影子题 148,做法几乎一模一样。

复杂度

时间O(m + n),两个链表的长度
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1 != null) {
cur.next = l1;
}
if (l2 != null) {
cur.next = l2;
}
return dummy.next;
}
}

JavaScript实现

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
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
let dummy = new ListNode(0);
let cur = dummy;
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1 !== null) {
cur.next = l1;
}
if (l2 !== null) {
cur.next = l2;
}
return dummy.next;
};

相关题目

1
2
3
4
5
21. Merge Two Sorted Lists
23. Merge k Sorted Lists
148. Sort List
1634. Add Two Polynomials Represented as Linked Lists
1940. Longest Common Subsequence Between Sorted Arrays

[LeetCode] 21. Merge Two Sorted Lists
https://shurui91.github.io/posts/1602189076.html
Author
Aaron Liu
Posted on
November 10, 2019
Licensed under