I have a linked list like this as my input (1) -> (2) -> (3) -> (-3) -> (4) -> NULL
And I wish to remove the consecutive nodes which have sum equal to zero i.e., I want my output linked list to be like this: (1) -> (2) -> (4) -> NULL
I have already solved this problem using approach of map and array, and then I came across the code shown below. And this code works perfectly fine for the the above test case and I'm unable to understand how?
/**
* 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) {
ListNode* new_head = new ListNode(0);
new_head->next = head;
ListNode* cur = new_head;
while(cur != NULL)
{
int sum=0;
while(head != NULL)
{
sum += head->val;
if(sum == 0)
{
cur->next = head->next;
}
head = head->next;
}
//What is happening here???
cur = cur->next;
if(cur != NULL)
{
head = cur->next;
}
}
return new_head->next;
}
};
Could someone please provide me with an explanation?