Skip to content

Commit

Permalink
Added Remove Nth Node From End of List
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 13, 2023
1 parent 7071f83 commit e276a09
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
40 changes: 40 additions & 0 deletions Medium/RemoveNthNodeFromEndOfList/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#pragma once

#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

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;
}
}
};
17 changes: 17 additions & 0 deletions Medium/RemoveNthNodeFromEndOfList/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit e276a09

Please sign in to comment.