Merge Two Linked Lists in a Specified Range C++ Solution
IntuitionTo merge list2 into list1 between indices a and b, we first need to identify two key positions in list1: the node just before index a (athNode) and the
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
![image.png](https://assets.leetcode.com/users/images/37e2ca51-59e6-4d13-9b9c-d9c0f4459ff4_1736066560.8633494.png)

To merge **list2** into **list1** between indices `a` and `b`, we first need to identify two key positions in **list1**: the node just before index `a` (`athNode`) and the node at index `b` (`bthNode`). Then, we find the last node of **list2**. After that, we update the pointers: set `athNode->next` to the head of **list2**, and link the last node of **list2** to `bthNode->next` (the node after `b`). This effectively merges **list2** into **list1** within the specified range.

# Approach
<!-- Describe your approach to solving the problem. -->
To solve this problem, we:

1. Traverse list1 to find the nodes at indices a-1 (just before the insertion point) and b (the last node to remove from list1).
2. Traverse list2 to find the last node.
3. Modify the next pointers of these key nodes to merge list2 between the nodes at positions a-1 and b in list1.
This approach ensures an efficient solution with a time complexity of O(b + m).

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(b+m)

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1)

The solution only uses a constant amount of extra space to store pointers (athNode, bthNode, and endNode). These pointers are used to navigate through the two lists, but they do not depend on the size of the input lists.
The solution does not create any new data structures (such as arrays or additional linked lists) that grow with the size of the input.
Thus, the space complexity is O(1), meaning the algorithm uses a constant amount of extra space.

# Code
```cpp []
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
        ListNode *athNode= list1;
        ListNode *bthNode = list1;
        ListNode *endNode = list2;
        for(int i=1;i<b+1;i++ ){
            if(i==a-1){
                athNode = bthNode->next;
            }
            bthNode = bthNode->next;
        }
        while(endNode->next!=NULL){
            endNode = endNode->next;
        }
        athNode->next = list2;
        endNode->next  = bthNode->next;
        return list1;
    }
    
};
```
['C++']