-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_2181.java
52 lines (49 loc) · 1.57 KB
/
_2181.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
package com.fishercoder.solutions.thirdthousand;
import com.fishercoder.common.classes.ListNode;
import java.util.ArrayList;
import java.util.List;
public class _2181 {
public static class Solution1 {
public ListNode mergeNodes(ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
ListNode pre = new ListNode(-1);
ListNode tmp = pre;
for (int i = 1; i < list.size(); i++) {
int sum = 0;
while (i < list.size() && list.get(i) != 0) {
sum += list.get(i);
i++;
}
tmp.next = new ListNode(sum);
tmp = tmp.next;
}
return pre.next;
}
}
public static class Solution2 {
/*
* Without using an extra list, do sum on the fly.
*/
public ListNode mergeNodes(ListNode head) {
ListNode pre = new ListNode(-1);
ListNode newHead = pre;
while (head != null && head.next != null) {
if (head.val == 0) {
int sum = 0;
head = head.next;
while (head.val != 0) {
sum += head.val;
head = head.next;
}
newHead.next = new ListNode(sum);
newHead = newHead.next;
}
}
return pre.next;
}
}
}