leetcode 1171 - Remove Zero Sum Consecutive Nodes from Linked List

https://leetcode.com/problems/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.

(Note that in the examples below, all sequences are serializations of ListNode objects.)

Example 1:

Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.
Example 2:

Input: head = [1,2,3,-3,4]
Output: [1,2,4]
Example 3:

Input: head = [1,2,3,-3,-2]
Output: [1]

Constraints:

The given linked list will contain between 1 and 1000 nodes.
Each node in the linked list has -1000 <= node.val <= 1000.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
*
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) {
stack<ListNode *> stk;
unordered_map<int, ListNode *> maps;

ListNode *new_head = NULL;
ListNode *node = head;
int total = 0;

maps[0] = (ListNode *)-1; //special node

while (node) {
ListNode *next = node->next;

int tmp = total + node->val;
if (ListNode *n = maps[tmp]) {
while (!stk.empty()) {
ListNode *top_node = stk.top();
if (top_node == n) {
break;
}
stk.pop();
maps.erase(total);
total -= top_node->val;
}
} else {
if (!stk.empty())
stk.top()->next = node;
else
new_head = node;
stk.push(node);

total += node->val;
maps[total] = node;
}

node = next;
}

if (!stk.empty())
stk.top()->next = NULL;
else
new_head = NULL;

return new_head;
}
};