# 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:
dummy = runner = ListNode(next=list1)
# move to position a
for _ in range(a):
runner = runner.next
# branch to list2
temp = runner
# move to position b in advance
for _ in range(b-a+2):
temp = temp.next
# from branch a, fill with list 2
while list2:
runner.next = list2
runner = runner.next
list2 = list2.next
# continue with branch b
while temp:
runner.next = temp
runner = runner.next
temp = temp.next
return dummy.next
Python
복사