题目链接
https://leetcode-cn.com/problems/merge-in-between-linked-lists/
题目
给你两个链表 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 <= list1.length <=
- 1 <= a <= b < list1.length - 1
- 1 <= list2.length <=
思路
见代码注释。
C++ Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* cur=list1;
int n=a-1;
//找到a前面的结点
while(n--) cur=cur->next; //此时cur指向a前面一个结点
ListNode* temp=cur->next; //temp指向结点a 从该结点起要删除
ListNode* cur2=temp->next; //cur2指向结点a后面的结点,便于删除结点a只后能继续遍历
cur->next=list2; //cur刚才指向a前面的结点,现在将其后面连上list2
n=b-a;
//遍历结点b及其前面的结点,全部删除,cur2最终指向b后面的结点
while(n--)
{
delete temp;
temp=cur2;
cur2=cur2->next;
}
//cur刚才在list2的头结点,现在将其继续遍历,移动到list2末端
while(cur->next!=nullptr)
{
cur=cur->next;
}
//将cur末端和list1删除后的部分(也就是cur2指向的结点)连接起来
cur->next=cur2;
return list1;
}
};