Remove Zero Sum Consecutive Nodes from Linked List in C++

Suppose we have given the head of a linked list; we have to repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. So after doing so, we have to return the head of the final linked list. So if the list is like [1,2,-3,3,1], then the result will be [3,1].

To solve this, we will follow these steps −

• Create a node called dummy, and store 0 into it, set next of dummy := head

• create one map m, store dummy for the key 0 into m, set sum = 0

• while head is not null −

• sum := sum + value of head, set m[sum] := head, and head := next of head

• head := dummy

• sum := 0

• while head is not null

• sum := sum + value of head

• temp := m[sum]

• if temp is not head, then next of head := next of temp

• return next of dummy

Let us see the following implementation to get better understanding −

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
ListNode *ptr = head;
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
ListNode* dummy = new ListNode(0);
unordered_map <int, ListNode*> m;
m[0] = dummy;
int sum = 0;
}
sum = 0;
ListNode* temp = m[sum];
}
}
return dummy->next;
}
};
main(){
vector<int> v1 = {1,2,-3,3,1};
ListNode *head = make_list(v1);
Solution ob;
}

Input

[1,2,-3,3,1]

Output

[3,1]

Updated on: 30-Apr-2020

2K+ Views