Merge a List In Between Two Positions
Problem statement
You are given two singly linked lists, list1 and list2, and two positions a and b in list1. Positions are counted from 0 at the head.
Remove the nodes of list1 at positions a through b, both included, and put the whole of list2 in their place: the node at position a - 1 must point to the head of list2, and the last node of list2 must point to the node that was at position b + 1.
Return the head of the resulting list.
Function
mergeInBetween(list1: ListNode, a: int, b: int, list2: ListNode) → ListNodeExamples
Example 1
list1 = [4,8,15,16,23,42]a = 2b = 3list2 = [7,7]return = [4,8,7,7,23,42]Positions 2 and 3 hold 15 and 16. They are removed, and 7 -> 7 goes between 8 (position 1) and 23 (position 4).
Example 2
list1 = [5,6,7]a = 1b = 1list2 = [100]return = [5,100,7]With a = b = 1 only the middle node 6 is removed and replaced by 100.
Example 3
list1 = [1,2,3,4,5,6,7]a = 1b = 5list2 = [9,8,7,6]return = [1,9,8,7,6,7]Everything between the first and the last node of list1 is removed. The first node 1 now points to 9, and list2's last node 6 points to the old last node 7.
Constraints
3 <= list1.length <= 10001 <= list2.length <= 10001 <= a <= b <= list1.length - 20 <= Node.val <= 10^9