Skip to content

Commit 8aa4612

Browse files
authored
Create remove-zero-sum-consecutive-nodes-from-linked-list.cpp
1 parent 36b80c5 commit 8aa4612

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode(int x) : val(x), next(NULL) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
ListNode* removeZeroSumSublists(ListNode* head) {
15+
ListNode dummy(0);
16+
auto curr = &dummy;
17+
dummy.next = head;
18+
int prefix = 0;
19+
OrderedDict<int, ListNode*> lookup;
20+
while (curr) {
21+
prefix += curr->val;
22+
auto node = curr;
23+
if (lookup.count(prefix)) {
24+
node = lookup[prefix];
25+
}
26+
while (lookup.count(prefix)) {
27+
lookup.popitem();
28+
}
29+
lookup[prefix] = node;
30+
node->next = curr->next;
31+
curr = curr->next;
32+
}
33+
return dummy.next;
34+
}
35+
36+
private:
37+
template<typename K, typename V>
38+
class OrderedDict {
39+
public:
40+
bool count(const K& key) const {
41+
return map_.count(key);
42+
}
43+
44+
V& operator[](const K& key) {
45+
if (!map_.count(key)) {
46+
list_.emplace_front();
47+
list_.begin()->first = key;
48+
map_[key] = list_.begin();
49+
}
50+
return map_[key]->second;
51+
}
52+
53+
void popitem() {
54+
auto del = list_.front(); list_.pop_front();
55+
map_.erase(del.first);
56+
}
57+
58+
private:
59+
list<pair<K, V>> list_;
60+
unordered_map<K, typename list<pair<K, V>>::iterator> map_;
61+
};
62+
};

0 commit comments

Comments
 (0)