-
Notifications
You must be signed in to change notification settings - Fork 6
/
RemoveConsecutiveNodesZeroSum.java
87 lines (71 loc) · 2.04 KB
/
RemoveConsecutiveNodesZeroSum.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
77
78
79
80
81
82
83
84
85
86
87
package com.dailyinterviewprojava.uber;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import com.dailyinterviewprojava.util.InputUtil;
import com.dailyinterviewprojava.util.ListNode;
/**
*
* @author ema
* Given a linked list of integers, remove all consecutive nodes that sum up to 0.
*
* Example:
* Input: 10 -> 5 -> -3 -> -3 -> 1 -> 4 -> -4
* Output: 10
*
* The consecutive nodes 5 -> -3 -> -3 -> 1 sums up to 0 so that sequence should be removed.
* 4 -> -4 also sums up to 0 too so that sequence should also be removed.
*
*/
public class RemoveConsecutiveNodesZeroSum {
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) {
listNode = listNode.next;
}
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;
}
}