-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1171. Remove zero sum consecutive nodes from linked list
56 lines (40 loc) · 1.35 KB
/
1171. Remove zero sum consecutive nodes from linked list
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
48
49
50
51
52
53
54
55
56
//1171. Remove zero sum consecutive nodes from linked list
import java.util.HashMap;
import java.util.Map;
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) {
Map<Integer, ListNode> map = new HashMap<>();
ListNode dummy = new ListNode(0);
dummy.next = head;
int prefixSum = 0;
map.put(prefixSum, dummy);
while(head != null) {
prefixSum += head.val;
if(map.containsKey(prefixSum)) {
ListNode start = map.get(prefixSum);
ListNode curr = start;
int sum = prefixSum;
while(curr != head) {
curr = curr.next;
sum += curr.val;
if(curr != head) {
map.remove(sum);
}
}
start.next = head.next;
}
else {
map.put(prefixSum, head);
}
head = head.next;
}
return dummy.next;
}
}