diff --git a/include/s0203_remove_linked_list_elements.hpp b/include/s0203_remove_linked_list_elements.hpp new file mode 100644 index 0000000..b72e06b --- /dev/null +++ b/include/s0203_remove_linked_list_elements.hpp @@ -0,0 +1,17 @@ +#ifndef S0203_REMOVE_LINKED_LIST_ELEMENTS_HPP +#define S0203_REMOVE_LINKED_LIST_ELEMENTS_HPP + +struct ListNode { + int val; + ListNode* next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode* next) : val(x), next(next) {} +}; + +class S0203 { + public: + ListNode* removeElements(ListNode* head, int val); +}; + +#endif diff --git a/src/s0203_remove_linked_list_elements.cpp b/src/s0203_remove_linked_list_elements.cpp new file mode 100644 index 0000000..9a43a9a --- /dev/null +++ b/src/s0203_remove_linked_list_elements.cpp @@ -0,0 +1,19 @@ +#include "s0203_remove_linked_list_elements.hpp" + +ListNode* S0203::removeElements(ListNode* head, int val) { + ListNode dummy = ListNode(0, head); + ListNode* ptr = &dummy; + while (ptr->next != nullptr) { + if (ptr->next->val == val) { + if (ptr->next->next == nullptr) { + ptr->next = nullptr; + break; + } else { + ptr->next = ptr->next->next; + } + } else { + ptr = ptr->next; + } + } + return dummy.next; +}