cpp: add «1669. Merge In Between Linked Lists»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
5549cdd7d8
commit
84ba9d343b
1 changed files with 34 additions and 0 deletions
34
cpp/merge-in-between-linked-lists.cpp
Normal file
34
cpp/merge-in-between-linked-lists.cpp
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
#ifdef _MF_TEST
|
||||||
|
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) {}
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
ListNode *mergeInBetween(ListNode *list1, int a, int b, ListNode *list2) {
|
||||||
|
auto left = list1;
|
||||||
|
for (int i = 1; i < a; ++i) {
|
||||||
|
left = left->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto right = left;
|
||||||
|
for (int i = a; i < b + 2; ++i) {
|
||||||
|
right = right->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
left->next = list2;
|
||||||
|
|
||||||
|
auto last_mid = list2;
|
||||||
|
while (last_mid->next != nullptr) {
|
||||||
|
last_mid = last_mid->next;
|
||||||
|
}
|
||||||
|
last_mid->next = right;
|
||||||
|
|
||||||
|
return list1;
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue