给你两个链表 list1 和 list2 ,它们包含的元素分别为 n 个和 m 个。
请你将 list1 中下标从 a 到 b 的全部节点都删除,并将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 <= 104
1 <= a <= b < list1.length - 1
1 <= list2.length <= 104来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-in-between-linked-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
ListNode before = list1, after = list1;
for (int i = 1; i < a; i++) {
before = before.next; //找到编号a之前的所有节点并定位到a-1节点 ,将list2的头连接在其之后
}
for (int i = 0; i <= b; i++) {
after = after.next; //找到编号b之后的所有节点并定位到编号为b+1的节点,将list2的尾连接在其之前
}
ListNode start = list2, end = list2;
while (end.next != null) {
end = end.next;
}
before.next = start;
end.next = after;
return list1;
}
}