文章目录
1669. 合并两个链表
方法:三指针法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
cur = ListNode(-1)
cur.next = list1
#定义三个指针 an,a_pre,bn
an,a_pre = cur.next,cur
bn = cur.next
countb = counta = 0
#同时寻找第a个节点和第b个节点
while countb <= b:
if counta < a:
an = an.next
a_pre = a_pre.next
counta += 1
bn = bn.next
countb += 1
#开始连接链表
a_pre.next = list2
while list2.next:
list2 = list2.next
list2.next = bn
return cur.next