
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
head := next of head
return next of dummy
Let us see the following implementation to get better understanding −
Example
#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]); } return head; } void print_list(ListNode *head){ 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); dummy->next = head; unordered_map <int, ListNode*> m; m[0] = dummy; int sum = 0; while(head){ sum += head->val; m[sum] = head; head = head->next; } head = dummy; sum = 0; while(head){ sum += head->val; ListNode* temp = m[sum]; if(temp != head){ head->next = temp->next; } head = head->next; } return dummy->next; } }; main(){ vector<int> v1 = {1,2,-3,3,1}; ListNode *head = make_list(v1); Solution ob; print_list(ob.removeZeroSumSublists(head)); }
Input
[1,2,-3,3,1]
Output
[3,1]