From 84ba9d343b8b8ea71b29006e3fca1fde7e4f8c76 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 21 Mar 2024 00:05:41 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB1669.=20Merge=20In=20Between?= =?UTF-8?q?=20Linked=20Lists=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/merge-in-between-linked-lists.cpp | 34 +++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 cpp/merge-in-between-linked-lists.cpp diff --git a/cpp/merge-in-between-linked-lists.cpp b/cpp/merge-in-between-linked-lists.cpp new file mode 100644 index 0000000..17d6c5b --- /dev/null +++ b/cpp/merge-in-between-linked-lists.cpp @@ -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; + } +};