1
var reverseEvenLengthGroups = function (head) {
2
let groupSize = 2;
3

4
let start = head;
5

6
let prev = head;
7
let curr = head.next;
8

9
let count = 0;
10

11
while (curr != null) {
12
if (count === groupSize) {
13
if (groupSize % 2 === 0) {
14
// we only reverse when it is even
15
const end = curr;
16
const tail = start.next; // the starting node of the reverse linked list will be the tail after the reverse takes place
17
reverseList(start, end, count); // we need to reverse everything in the middle of start and end
18
start = tail; // we set the new start to the end of the reversed linked list
19
} else {
20
// when groupSize is even we don't need to reverse, but need to set the new start to the prev node
21
start = prev;
22
}
23
count = 0; // whenever we reached the group size we need to reset our count and up our groupSize
24
++groupSize;
25
} else {
26
// just a normal traversal when we haven't hit our groupSize
27
prev = curr;
28
curr = curr.next;
29
++count;
30
}
31
}
32

33
if (count % 2 === 0) {
34
// in the case where we ended early on even count
35
reverseList(start, null, count);
36
}
37

38
return head;
39

40
function reverseList(start, end, count) {
41
if (start.next == null) return start; // for case when we have a single node
42

43
let prev = start;
44

45
let curr = start.next;
46
let tail = start.next;
47

48
for (let i = 0; i < count; ++i) {
49
const next = curr.next;
50
curr.next = prev;
51
prev = curr;
52
curr = next;
53
}
54

55
start.next = prev;
56
tail.next = end;
57

58
return;
59
}
60
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0