From 37d6c3400c3e0350661c37a53bb0c552f5561e08 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 12 Mar 2024 23:49:58 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB1171.=20Remove=20Zero=20Sum?= =?UTF-8?q?=20Consecutive=20Nodes=20from=20Linked=20List=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...sum-consecutive-nodes-from-linked-list.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 cpp/remove-zero-sum-consecutive-nodes-from-linked-list.cpp diff --git a/cpp/remove-zero-sum-consecutive-nodes-from-linked-list.cpp b/cpp/remove-zero-sum-consecutive-nodes-from-linked-list.cpp new file mode 100644 index 0000000..7f419d3 --- /dev/null +++ b/cpp/remove-zero-sum-consecutive-nodes-from-linked-list.cpp @@ -0,0 +1,43 @@ +#include + +#ifdef _MF_TEST +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) {} +}; +#endif + +class Solution { + public: + ListNode *removeZeroSumSublists(ListNode *head) { + ListNode front(0, head); + + std::unordered_map sums; + + int sum = 0; + for (ListNode *node = &front; node != nullptr; node = node->next) { + sum += node->val; + + if (auto it = sums.find(sum); it != sums.end()) { + auto prev = it->second; + node = prev->next; + + int p = sum + node->val; + while (p != sum) { + sums.erase(p); + node = node->next; + p += node->val; + } + + prev->next = node->next; + } else { + sums[sum] = node; + } + } + + return front.next; + } +};