Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f8fa91f

Browse files
Add Solution.java for 1171.Remove Zero Sum Consecutive Nodes from Linked
List
1 parent 4414248 commit f8fa91f

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Remove Zero Sum Consecutive Nodes from Linked List
2+
3+
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
4+
5+
After doing so, return the head of the final linked list. You may return any such answer.
6+
7+
(Note that in the examples below, all sequences are serializations of ListNode objects.)
8+
9+
## Example 1:
10+
```
11+
Input: head = [1,2,-3,3,1]
12+
Output: [3,1]
13+
Note: The answer [1,2,1] would also be accepted.
14+
```
15+
16+
## Example 2:
17+
```
18+
Input: head = [1,2,3,-3,4]
19+
Output: [1,2,4]
20+
```
21+
22+
## Example 3:
23+
```
24+
Input: head = [1,2,3,-3,-2]
25+
Output: [1]
26+
```
27+
28+
29+
## Constraints:
30+
31+
* The given linked list will contain between 1 and 1000 nodes.
32+
* Each node in the linked list has -1000 <= node.val <= 1000.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public ListNode removeZeroSumSublists(ListNode head) {
11+
Map<Integer, ListNode> map = new HashMap<>();
12+
boolean isZeroSum = true;
13+
14+
while (isZeroSum) {
15+
isZeroSum = false;
16+
int sum = 0;
17+
ListNode temp = head;
18+
19+
while (temp != null) {
20+
sum += temp.val;
21+
22+
if (sum == 0) {
23+
head = temp.next;
24+
map.clear();
25+
isZeroSum = true;
26+
break;
27+
} else if (map.containsKey(sum)) {
28+
map.get(sum).next = temp.next;
29+
map.clear();
30+
isZeroSum = true;
31+
break;
32+
}
33+
34+
map.put(sum, temp);
35+
temp = temp.next;
36+
}
37+
}
38+
39+
return head;
40+
}
41+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /