Skip to content

Commit cee6733

Browse files
authored
Create 2074-reverse-nodes-in-even-length-groups.js
1 parent b80d481 commit cee6733

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
const reverseEvenLengthGroups = function(head) {
13+
const arr = []
14+
let cur = head
15+
while(cur) {
16+
arr.push(cur)
17+
cur = cur.next
18+
}
19+
let len = 1, res = []
20+
for(let i = 0, n = arr.length; i < n; ) {
21+
let backup = len, tmp = [], rev = len % 2 === 0
22+
while(len && i < n) {
23+
tmp.push(arr[i])
24+
i++
25+
len--
26+
}
27+
if((tmp.length % 2 === 0) ) {
28+
tmp.reverse()
29+
}
30+
res.push(...tmp)
31+
len = backup + 1
32+
}
33+
for(let i = 0; i < res.length; i++) {
34+
if(i === res.length - 1) res[i].next = null
35+
else {
36+
res[i].next = res[i + 1]
37+
}
38+
}
39+
40+
return res[0]
41+
};

0 commit comments

Comments
 (0)