1669. Merge in Between Linked Lists #
题目 #
给定两个链表list1
和list2
,它们包含的元素分别为n
个和m
个。
将list1
中下标从a
到b
的全部节点都删除,并将list2
接在被删除节点的位置。
思路 #
代码 #
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 ptrA = list1, ptrB = list1;
for (int i=0; i<a-1; i++) ptrA = ptrA.next;
for (int i=0; i<b; i++) ptrB = ptrB.next;
ListNode rear = list2;
while (rear.next != null) rear = rear.next;
ptrA.next = list2;
rear.next = ptrB.next;
return list1;
}
}