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

C++Server Side ProgrammingProgramming

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 := 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){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* dummy = new ListNode(0);
unordered_map <int, ListNode*> m;
m = dummy;
int sum = 0;
}
sum = 0;
ListNode* temp = m[sum];
}
}
return dummy->next;
}
};
main(){
vector<int> v1 = {1,2,-3,3,1};
}
[1,2,-3,3,1]
[3,1]