-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove0sumNode1171.java
More file actions
35 lines (30 loc) · 1.07 KB
/
remove0sumNode1171.java
File metadata and controls
35 lines (30 loc) · 1.07 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
public class remove0sumNode1171 {
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; }
}
/*
Given the head of a linked list, we repeatedly delete consecutive
sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list.
You may return any such answer.
*/
public ListNode removeZeroSumSublists(ListNode head) {
ListNode node = new ListNode (0 , head) ;
ListNode curr = node;
while (curr != null ) {
int sum =0 ;
ListNode temp = curr.next ;
while (temp != null ) {
sum += temp.val ;
if (sum == 0)curr.next = temp.next;
temp = temp.next;
}
curr = curr.next;
}
return node.next;
}
}