From 4c9cdfb6402f4068544051baccebc9cf6e5c493f Mon Sep 17 00:00:00 2001 From: Ace-Krypton Date: Thu, 14 Sep 2023 23:18:25 +0200 Subject: [PATCH] Added Remove Duplicates From List --- CMakeLists.txt | 11 +++++ .../include/solution.hpp | 42 +++++++++++++++++++ .../tests/test.cpp | 18 ++++++++ 3 files changed, 71 insertions(+) create mode 100644 Easy/RemoveDuplicatesFromSortedList/include/solution.hpp create mode 100644 Easy/RemoveDuplicatesFromSortedList/tests/test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9dde60e..f80b97d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -733,4 +733,15 @@ add_executable(LRUCache target_link_libraries( LRUCache GTest::gtest_main +) + +# Remove Duplicates from Sorted List +add_executable(RemoveDuplicatesFromSortedList + Easy/RemoveDuplicatesFromSortedList/include/solution.hpp + Easy/RemoveDuplicatesFromSortedList/tests/test.cpp +) + +target_link_libraries( + RemoveDuplicatesFromSortedList + GTest::gtest_main ) \ No newline at end of file diff --git a/Easy/RemoveDuplicatesFromSortedList/include/solution.hpp b/Easy/RemoveDuplicatesFromSortedList/include/solution.hpp new file mode 100644 index 0000000..b497d06 --- /dev/null +++ b/Easy/RemoveDuplicatesFromSortedList/include/solution.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include +#include +#include + +struct ListNode { + int32_t value; + ListNode *next; +}; + +class Solution { +public: + static auto delete_duplicates(ListNode* head) -> ListNode* { + if (!head || !head->next) return head; + ListNode *current = head; + + while (current != nullptr && current->next != nullptr) { + if (current->value == current->next->value) { + current->next = current->next->next; + } else current = current->next; + } + + return head; + } + + static auto insert(ListNode **head_ref, 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/Easy/RemoveDuplicatesFromSortedList/tests/test.cpp b/Easy/RemoveDuplicatesFromSortedList/tests/test.cpp new file mode 100644 index 0000000..3f1e0e5 --- /dev/null +++ b/Easy/RemoveDuplicatesFromSortedList/tests/test.cpp @@ -0,0 +1,18 @@ +#include "../include/solution.hpp" + +auto main() -> int { + ListNode *node = nullptr; + Solution::insert(&node, 3); + Solution::insert(&node, 3); + Solution::insert(&node, 2); + Solution::insert(&node, 1); + Solution::insert(&node, 1); + + Solution::print(node); + std::cout << '\n'; + node = Solution::delete_duplicates(node); + Solution::print(node); + delete node; + + return 0; +}