题目链接
Leetcode.1669 合并两个链表 Rating : 1428
题目描述
给你两个链表 list1
和 list2
,它们包含的元素分别为 n
个和 m
个。
请你将 list1
中下标从 a
到 b
的全部节点都删除,并将list2
接在被删除节点的位置。
示例 1:
输入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
输出:[0,1,2,1000000,1000001,1000002,5]
解释:我们删除 list1 中下标为 3 和 4 的两个节点,并将 list2 接在该位置。上图中蓝色的边和节点为答案链表。
示例 2:
输入:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
输出:[0,1,1000000,1000001,1000002,1000003,1000004,6]
解释:上图中蓝色的边和节点为答案链表。
提示:
- 3 < = l i s t 1. l e n g t h < = 1 0 4 3 <= list1.length <= 10^4 3<=list1.length<=104
- 1 < = a < = b < l i s t 1. l e n g t h − 1 1 <= a <= b < list1.length - 1 1<=a<=b<list1.length−1
- 1 < = l i s t 2. l e n g t h < = 1 0 4 1 <= list2.length <= 10^4 1<=list2.length<=104
分析:
时间复杂度: O ( n ) O(n) O(n)
C++代码:
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* start = list1,*end = list1;
for(int i = 0;i < a - 1;i++) start = start->next;
for(int i = 0;i < b + 1;i++) end = end->next;
start->next = list2;
ListNode* cur = list2;
while(cur->next){
cur = cur->next;
}
cur->next = end;
return list1;
}
};
Java代码:
class Solution {
public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
ListNode start = list1;
ListNode end = list1;
for(int i = 0;i < a - 1;i++){
start = start.next;
}
for(int j = 0;j < b+1;j++){
end = end.next;
}
start.next = list2;
ListNode cur = list1;
while(cur.next!=null){
cur = cur.next;
}
cur.next = end;
return list1;
}
}