-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2074-reverse-nodes-in-even-length-groups.js
More file actions
72 lines (64 loc) · 1.85 KB
/
2074-reverse-nodes-in-even-length-groups.js
File metadata and controls
72 lines (64 loc) · 1.85 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* 2074. Reverse Nodes in Even Length Groups
* https://leetcode.com/problems/reverse-nodes-in-even-length-groups/
* Difficulty: Medium
*
* You are given the head of a linked list.
*
* The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form
* the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number
* of nodes assigned to it. In other words:
* - The 1st node is assigned to the first group.
* - The 2nd and the 3rd nodes are assigned to the second group.
* - The 4th, 5th, and 6th nodes are assigned to the third group, and so on.
*
* Note that the length of the last group may be less than or equal to 1 + the length of the second
* to last group.
*
* Reverse the nodes in each group with an even length, and return the head of the modified linked
* list.
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseEvenLengthGroups = function(head) {
let prevGroup = head;
let groupLength = 2;
while (prevGroup.next) {
let count = 0;
let current = prevGroup.next;
const groupStart = current;
while (current && count < groupLength) {
current = current.next;
count++;
}
if (count % 2 === 0) {
prevGroup.next = reverseGroup(groupStart, count);
}
for (let i = 0; i < count; i++) {
prevGroup = prevGroup.next;
}
groupLength++;
}
return head;
function reverseGroup(start, length) {
let prev = null;
let current = start;
for (let i = 0; i < length; i++) {
const next = current.next;
current.next = prev;
prev = current;
current = next;
}
start.next = current;
return prev;
}
};