LeetCode-21-合并两个有序链表

题目

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

示例 1:

img
1
2
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

1
2
输入:l1 = [], l2 = []
输出:[]

示例 3:

1
2
输入:l1 = [], l2 = [0]
输出:[0]

提示:

  • 两个链表的节点数目范围是 [0, 50]
  • -100 <= Node.val <= 100
  • l1l2 均按 非递减顺序 排列

题解

这一题同样在时间复杂度干掉了100%,由于使用了额外的链表,所以空间复杂度就差很多了。

其实是有点类似双指针的方法,我们用res链表保存合并的结果,两个指针分别遍历list1list2,遇到小的数字,就把它连接到res上,然后用了哪个链表的数据,哪个链表就往后移动,另一个链表不变;一直都遍历到list1list2的末尾。

这里我把当前节点为空的时候的数字用-101表示了,这个地方要解释一下,方便后面的数据比较。

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode res = new ListNode();
ListNode index = res;
if (list1 == null && list2 == null) { // 特殊处理都为空的情况
return null;
}
while (list1 != null || list2 != null) {
// 需要注意一个到末尾了,一个没到末尾
int num1, num2;
if (list1 == null) {
num1 = -101;
} else {
num1 = list1.val;
}
if (list2 == null) {
num2 = -101;
} else {
num2 = list2.val;
}
if (num1 == -101) { // 表示list1为空了,连接list2就行
index.val = num2;
if (list2 != null) {
list2 = list2.next;
}
} else if (num2 == -101) { // 表示list2为空了,连接list1就行
index.val = num1;
if (list1 != null) {
list1 = list1.next;
}
}else if (num1 <= num2) { // 都不为空,比较大小
index.val = num1;
if (list1 != null) {
list1 = list1.next;
}
} else {
index.val = num2;
if (list2 != null) {
list2 = list2.next;
}
}
if (list1 != null || list2 != null) { // 判断后面是否还需要节点进行连接
ListNode temp = new ListNode(-101, null);
index.next = temp;
}

if (list1 != null || list2 != null) { // 判断index是否需要往后走
index = index.next;
}
}
return res;
}
}

LeetCode-21-合并两个有序链表
https://excelius.xyz/leetcode-21-合并两个有序链表/
作者
Ther
发布于
2024年7月14日
许可协议