-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathRemoveZeroSumConsecutiveNodesFromLinkedList.java
82 lines (80 loc) · 2.3 KB
/
RemoveZeroSumConsecutiveNodesFromLinkedList.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
/*https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/*/
/**
* 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) {
Map<Integer,ListNode> map = new HashMap<Integer,ListNode>();
ListNode temp = head, prev = head;
int sum = 0;
while (temp != null)
{
sum += temp.val;
if (temp.val == 0)
{
if (head == temp)
{
head = head.next;
prev = head;
}
else prev.next = temp.next;
temp = temp.next;
}
else if (sum == 0)
{
head = temp.next;
prev = head;
temp = head;
map.clear();
}
else if (map.containsKey(sum))
{
ListNode start = map.get(sum);
ListNode next = start.next;
start.next = temp.next;
int copy = sum;
while (next != temp)
{
copy += next.val;
map.remove(copy);
next = next.next;
}
prev = start;
temp = temp.next;
}
else
{
map.put(sum,temp);
prev = temp;
temp = temp.next;
}
}
return head;
}
}
/**
* 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) {
if (head == null) return head;
int s = 0;
for (ListNode cur = head; cur != null; cur = cur.next) if ((s += cur.val) == 0) return removeZeroSumSublists(cur.next);
head.next = removeZeroSumSublists(head.next);
return head;
}
}