題解:
模拟链表操作
/**
* 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) {
int i = 0;
ListNode head = new ListNode(-1, list1);
ListNode index = list1;
ListNode right = null;
ListNode left = null;
// 拿到删除始节点的前一个节点
while (i < a - 1 && index != null) {
index = index.next;
i++;
}
left = index;
if (a == 0) head.next = list2;
// 拿到删除末节点的后一个节点
while (i < b + 1 && index != null) {
index = index.next;
i++;
}
right = index;
// 拼接
left.next = list2;
while (list2.next != null) {
list2 = list2.next;
}
list2.next = right;
// 返回开头
return head.next;
}
}
标签:index,ListNode,val,int,合并,next,链表,1669,list2
From: https://www.cnblogs.com/eiffelzero/p/17077116.html