From e276a099cd0ed0666017944b06156702210bd02f Mon Sep 17 00:00:00 2001 From: Ace-Krypton Date: Wed, 13 Sep 2023 21:40:39 +0200 Subject: [PATCH] Added Remove Nth Node From End of List --- CMakeLists.txt | 11 +++++ .../include/solution.hpp | 40 +++++++++++++++++++ .../RemoveNthNodeFromEndOfList/tests/test.cpp | 17 ++++++++ 3 files changed, 68 insertions(+) create mode 100644 Medium/RemoveNthNodeFromEndOfList/include/solution.hpp create mode 100644 Medium/RemoveNthNodeFromEndOfList/tests/test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0323b4f..6da1805 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -678,4 +678,15 @@ add_executable(PalindromeLinkedList target_link_libraries( PalindromeLinkedList GTest::gtest_main +) + +# Remove Nth Node From End Of List +add_executable(RemoveNthNodeFromEndOfList + Medium/RemoveNthNodeFromEndOfList/include/solution.hpp + Medium/RemoveNthNodeFromEndOfList/tests/test.cpp +) + +target_link_libraries( + RemoveNthNodeFromEndOfList + GTest::gtest_main ) \ No newline at end of file diff --git a/Medium/RemoveNthNodeFromEndOfList/include/solution.hpp b/Medium/RemoveNthNodeFromEndOfList/include/solution.hpp new file mode 100644 index 0000000..67f222a --- /dev/null +++ b/Medium/RemoveNthNodeFromEndOfList/include/solution.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include +#include + +struct ListNode { + int32_t value; + ListNode *next; +}; + +class Solution { +public: + static auto remove_Nth_from_end(ListNode *head, int32_t n) -> ListNode* { + auto *dummy = new ListNode(0); + dummy->next = head; + ListNode *slow = dummy, *fast = dummy; + for (std::size_t i = 0; i <= n; ++i) fast = fast->next; + while (fast) slow = slow->next, fast = fast->next; + slow->next = slow->next->next; + head = dummy->next; + delete dummy; + 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/Medium/RemoveNthNodeFromEndOfList/tests/test.cpp b/Medium/RemoveNthNodeFromEndOfList/tests/test.cpp new file mode 100644 index 0000000..0133059 --- /dev/null +++ b/Medium/RemoveNthNodeFromEndOfList/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'; + Solution::remove_Nth_from_end(node, 2); + Solution::print(node); + + return 0; +}