[LeetCode] Remove Zero Sum Consecutive Nodes from Linked List

1171. Remove Zero Sum Consecutive Nodes from Linked List

Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.

After doing so, return the head of the final linked list. You may return any such answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* 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* removeZeroSumSublists(ListNode* head) {
ListNode* dummy = new ListNode(0, head);
ListNode* runner = dummy;
unordered_set<int> us;
vector<pair<int, ListNode*>> st;
int sum = 0;

while(runner) {
sum += runner->val;
while(runner->next and runner->next->val == 0)
runner->next = runner->next->next;
if(us.count(sum)) {
while(!st.empty() and st.back().first != sum) {
us.erase(st.back().first);
st.pop_back();
}
st.back().second->next = runner->next;
sum = st.back().first;
} else {
us.insert(sum);
st.push_back({sum, runner});
}

runner = runner->next;
}

return dummy->next;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/04/PS/LeetCode/remove-zero-sum-consecutive-nodes-from-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.