Skip to content

Commit 4fed490

Browse files
add a solution for 2181
1 parent 5866de4 commit 4fed490

File tree

1 file changed

+23
-0
lines changed
  • src/main/java/com/fishercoder/solutions/thirdthousand

1 file changed

+23
-0
lines changed

src/main/java/com/fishercoder/solutions/thirdthousand/_2181.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,27 @@ public ListNode mergeNodes(ListNode head) {
2727
return pre.next;
2828
}
2929
}
30+
31+
public static class Solution2 {
32+
/**
33+
* Without using an extra list, do sum on the fly.
34+
*/
35+
public ListNode mergeNodes(ListNode head) {
36+
ListNode pre = new ListNode(-1);
37+
ListNode newHead = pre;
38+
while (head != null && head.next != null) {
39+
if (head.val == 0) {
40+
int sum = 0;
41+
head = head.next;
42+
while (head.val != 0) {
43+
sum += head.val;
44+
head = head.next;
45+
}
46+
newHead.next = new ListNode(sum);
47+
newHead = newHead.next;
48+
}
49+
}
50+
return pre.next;
51+
}
52+
}
3053
}

0 commit comments

Comments
 (0)