1669. Merge in Between Linked Lists

1669. Merge in Between Linked Lists #

题目 #

给定两个链表list1list2,它们包含的元素分别为n个和m个。

list1中下标从ab的全部节点都删除,并将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;
    }
}