From 72a16c8d6a6f1fc6732e57d47c0321a0c6e77ca6 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Mon, 24 Feb 2025 23:28:47 +0800 Subject: [PATCH] feat: 83_remove_duplicates_from_sorted_list --- .../main.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 83_remove_duplicates_from_sorted_list/main.cpp diff --git a/83_remove_duplicates_from_sorted_list/main.cpp b/83_remove_duplicates_from_sorted_list/main.cpp new file mode 100644 index 0000000..05d8835 --- /dev/null +++ b/83_remove_duplicates_from_sorted_list/main.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +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 Solution { + public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* currentNode = head; + ListNode* lastNode = nullptr; + + while (currentNode != nullptr) { + if (lastNode && lastNode->val == currentNode->val) { + lastNode->next = currentNode->next; + delete currentNode; + currentNode = lastNode->next; + } else { + lastNode = currentNode; + currentNode = currentNode->next; + } + } + + return head; + } +}; \ No newline at end of file