Skip to content

Commit 6a73384

Browse files
authored
Create 1669. Merge In Between Linked Lists
1 parent e8a5d65 commit 6a73384

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

1669. Merge In Between Linked Lists

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
14+
ListNode* dummy = new ListNode();
15+
dummy->next = list1;
16+
17+
ListNode* prevA = dummy;
18+
for (int i = 0; i < a; ++i) {
19+
prevA = prevA->next;
20+
}
21+
22+
ListNode* prevB = prevA;
23+
for (int i = a; i <= b + 1; ++i) {
24+
prevB = prevB->next;
25+
}
26+
27+
ListNode* list2Tail = list2;
28+
while (list2Tail->next != nullptr) {
29+
list2Tail = list2Tail->next;
30+
}
31+
32+
prevA->next = list2;
33+
list2Tail->next = prevB;
34+
35+
return dummy->next;
36+
}
37+
};

0 commit comments

Comments
 (0)