-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution1171.java
More file actions
49 lines (47 loc) · 1.39 KB
/
Copy pathSolution1171.java
File metadata and controls
49 lines (47 loc) · 1.39 KB
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
package medium;
public class Solution1171 {
public static void main(String[] args) {
Solution1171 solution = new Solution1171();
int[][] cases = {
{1, 2, -3, 3, 0, 1},
{1, -1}
};
for (int[] c : cases) {
ListNode head = new ListNode(0);
ListNode temp = head;
for (int i : c) temp = temp.next = new ListNode(i);
temp = solution.removeZeroSumSublists(head.next);
while (temp != null) {
System.out.print(temp.val + " ");
temp = temp.next;
}
System.out.println();
}
}
public ListNode removeZeroSumSublists(ListNode head) {
ListNode temp = head;
head = new ListNode(0);
head.next = temp;
while (temp != null) {
ListNode t = head;
while (t != temp) {
t.val += temp.val;
if (t.val == 0) {
t.next = temp.next;
break;
}
t = t.next;
}
temp.val = 0;
temp = temp.next;
}
if (head.next == null) return null;
temp = head;
while (temp != null) {
temp.val -= temp.next.val;
if (temp.next.val == 0) temp.next = null;
temp = temp.next;
}
return head;
}
}