Skip to content

Commit 2a5e936

Browse files
authored
Create merge-in-between-linked-lists.cpp
1 parent da9d250 commit 2a5e936

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/merge-in-between-linked-lists.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(m + n)
2+
// Space: O(1)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode() : val(0), next(nullptr) {}
10+
* ListNode(int x) : val(x), next(nullptr) {}
11+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
12+
* };
13+
*/
14+
class Solution {
15+
public:
16+
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
17+
ListNode* prev_first = nullptr, *last = list1;
18+
for (int i = 0; i < b; ++i) {
19+
if (i == a - 1) {
20+
prev_first = last;
21+
}
22+
last = last->next;
23+
}
24+
prev_first->next = list2;
25+
for (; list2->next; list2 = list2->next);
26+
list2->next = last->next;
27+
last->next = nullptr;
28+
return list1;
29+
}
30+
};

0 commit comments

Comments
 (0)