Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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) {
- unordered_map<int, ListNode*> map;
- ListNode *dummy = new ListNode(0, head);
- map[0] = dummy;
- int sum = 0;
- while(head){
- sum += head->val;
- if(map.find(sum) != map.end()){
- ListNode* curr = map[sum]->next;
- int tsum = sum + curr->val;
- while(tsum != sum){
- map.erase(tsum);
- curr = curr->next;
- tsum += curr->val;
- }
- map[sum]->next = head->next;
- }
- else{
- map[sum] = head;
- }
- head = head->next;
- }
- return dummy->next;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement