-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveZeroSumSublists.java
76 lines (60 loc) · 1.73 KB
/
RemoveZeroSumSublists.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.leetcode.algorithms.medium.linkedlist;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
import com.leetcode.util.ListNode;
public class RemoveZeroSumSublists {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
ListNode listNode = null;
for (int i = 0; i < inputs.length; i++) {
listNode = insertListNode(listNode, Integer.parseInt(inputs[i]));
}
// Remove zero sum sublists
listNode = removeZeroSumSublists(listNode);
// Print output
while (listNode != null) {
System.out.print(listNode.val + ",");
listNode = listNode.next;
}
System.out.println();
scanner.close();
}
static ListNode insertListNode(ListNode listNode, int val) {
if (listNode == null) {
listNode = new ListNode(val);
} else {
listNode.next = insertListNode(listNode.next, val);
}
return listNode;
}
static ListNode removeZeroSumSublists(ListNode head) {
Map<Integer, ListNode> map = new HashMap<>();
boolean isZeroSum = true;
while (isZeroSum) {
isZeroSum = false;
int sum = 0;
ListNode temp = head;
while (temp != null) {
sum += temp.val;
if (sum == 0) {
head = temp.next;
map.clear();
isZeroSum = true;
break;
} else if (map.containsKey(sum)) {
map.get(sum).next = temp.next;
map.clear();
isZeroSum = true;
break;
}
map.put(sum, temp);
temp = temp.next;
}
}
return head;
}
}