Skip to content

Commit e606b4d

Browse files
authored
Create 2181-merge-nodes-in-between-zeros.js
1 parent 37a41a8 commit e606b4d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

2181-merge-nodes-in-between-zeros.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {ListNode}
11+
*/
12+
var mergeNodes = function(head) {
13+
const dummy = new ListNode()
14+
const arr = []
15+
let cur = head
16+
while(cur) {
17+
arr.push(cur)
18+
cur = cur.next
19+
}
20+
let tail = dummy
21+
let lastIdx = 0, sum = 0
22+
if(arr.length) {
23+
for(let i = 1; i < arr.length; i++) {
24+
const tmp = arr[i]
25+
if(tmp.val === 0 && sum !== 0) {
26+
lastIdx = i
27+
tail.next = new ListNode(sum)
28+
tail = tail.next
29+
sum = 0
30+
} else {
31+
sum += tmp.val
32+
}
33+
}
34+
}
35+
36+
return dummy.next
37+
};

0 commit comments

Comments
 (0)