-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove_Zero_Sum_Consecutive_Nodes_from_Linked_List.java
47 lines (39 loc) · 1.33 KB
/
Remove_Zero_Sum_Consecutive_Nodes_from_Linked_List.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeZeroSumSublists(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
// Create a hashmap to store cumulative sums
Map<Integer, ListNode> map = new HashMap<>();
int sum = 0;
ListNode curr = dummy;
while (curr != null) {
sum += curr.val;
if (map.containsKey(sum)) {
// Remove nodes between the two cumulative sums
ListNode prev = map.get(sum).next;
int tempSum = sum;
while (prev != curr) {
tempSum += prev.val;
map.remove(tempSum);
prev = prev.next;
}
// Update the next pointer of the previous node
map.get(sum).next = curr.next;
} else {
map.put(sum, curr);
}
curr = curr.next;
}
return dummy.next;
}
}