---
tags: leetcode
---
# [1669. Merge In Between Linked Lists](https://leetcode.com/problems/merge-in-between-linked-lists/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ 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 *left = list1, *right = list1;
for (int i = 1; i < a; ++i) {
left = left->next;
right = right->next;
}
right = right->next;
int diff = b - a + 1;
while (diff > 0) {
ListNode *x = right;
right = right->next;
delete x;
--diff;
}
ListNode *list2Tail = list2;
while (list2Tail->next != nullptr) {
list2Tail = list2Tail->next;
}
left->next = list2;
list2Tail->next = right;
return list1;
}
};
```
## Time Complexity
$O(n1 + n2)$
$n1$ is the number of nodes in the linked list referred by `list1`.
$n2$ is the number of nodes in the linked list referred by `list2`.
## Space Complexity
$O(1)$
# Miscellaneous
<!--
# Test Cases
```
[0,1,2,3,4,5]
3
4
[1000000,1000001,1000002]
```
```
[0,1,2,3,4,5,6]
2
5
[1000000,1000001,1000002,1000003,1000004]
```
-->