From bda7ae3d60c25c091d86c4e441f9535d2427e20f Mon Sep 17 00:00:00 2001 From: Ace-Krypton Date: Tue, 3 Oct 2023 19:58:13 +0200 Subject: [PATCH] Added Odd Even Linked List --- CMakeLists.txt | 11 +++++ Medium/OddEvenLinkedList/include/solution.hpp | 47 +++++++++++++++++++ Medium/OddEvenLinkedList/tests/test.cpp | 17 +++++++ 3 files changed, 75 insertions(+) create mode 100644 Medium/OddEvenLinkedList/include/solution.hpp create mode 100644 Medium/OddEvenLinkedList/tests/test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 34f4cf3..3b89f74 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1272,4 +1272,15 @@ add_executable(NumberOfGoodPairs target_link_libraries( NumberOfGoodPairs GTest::gtest_main +) + +# Odd Even Linked List +add_executable(OddEvenLinkedList + Medium/OddEvenLinkedList/include/solution.hpp + Medium/OddEvenLinkedList/tests/test.cpp +) + +target_link_libraries( + OddEvenLinkedList + GTest::gtest_main ) \ No newline at end of file diff --git a/Medium/OddEvenLinkedList/include/solution.hpp b/Medium/OddEvenLinkedList/include/solution.hpp new file mode 100644 index 0000000..850b4f6 --- /dev/null +++ b/Medium/OddEvenLinkedList/include/solution.hpp @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include +#include + +struct ListNode { + int32_t value; + ListNode *next; +}; + +class Solution { +public: + static auto odd_even_list(ListNode *head) -> ListNode* { + if (head == nullptr) return nullptr; + + ListNode *odd = head; + ListNode *even = head->next; + ListNode *even_head = head->next; + + while (even && even->next) { + odd->next = odd->next->next; + even->next = even->next->next; + odd = odd->next; + even = even->next; + } + + odd->next = even_head; + return head; + } + + static auto insert(ListNode **head_ref, + const int32_t new_value) -> void { + auto *node = new ListNode(); + node->value = new_value; + node->next = (*head_ref); + (*head_ref) = node; + } + + static auto print(ListNode *head) -> void { + while (head != nullptr) { + std::cout << head->value << ' '; + head = head->next; + } + } +}; diff --git a/Medium/OddEvenLinkedList/tests/test.cpp b/Medium/OddEvenLinkedList/tests/test.cpp new file mode 100644 index 0000000..a69fbda --- /dev/null +++ b/Medium/OddEvenLinkedList/tests/test.cpp @@ -0,0 +1,17 @@ +#include "../include/solution.hpp" + +auto main() -> int { + ListNode *node = nullptr; + Solution::insert(&node, 5); + Solution::insert(&node, 4); + Solution::insert(&node, 3); + Solution::insert(&node, 2); + Solution::insert(&node, 1); + + Solution::print(node); + std::cout << '\n'; + node = Solution::odd_even_list(node); + Solution::print(node); + + return 0; +}