Skip to content

Commit

Permalink
Added Remove Duplicates From List
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 14, 2023
1 parent 9d6b510 commit 4c9cdfb
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
42 changes: 42 additions & 0 deletions Easy/RemoveDuplicatesFromSortedList/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#pragma once

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

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

0 comments on commit 4c9cdfb

Please sign in to comment.