Reverse Nodes In Even Length Groups
Given the head of a linked list, the nodes in it are assigned to each group in a sequential manner. The length of these groups follows the sequence of natural numbers. Natural numbers are positive whole numbers denoted by (1, 2, 3, 4, ...).
In other words:
- The 1st node is assigned to the first group.
- The 2nd and 3rd nodes are assigned to the second group.
- The 4th, 5th, and 6th nodes are assigned to the third group, and so on.
Your task is to reverse the nodes in each group with an even number of nodes and return the head of the modified linked list.
Note: The length of the last group may be less than or equal to 1 + the length of the second-to-last group.
Constraints
- 1 ≤ Number of nodes ≤ 500
- 0 ≤
LinkedListNode.data
Examples
(The original source references an illustration image for this section, which isn't available here. Below is a worked example based on the problem's grouping logic.)
Example 1
Input:
head = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation:
- Group 1 (length 1):
[1]→ odd length, stays the same. - Group 2 (length 2):
[2, 3]→ even length, reversed to[3, 2]. - Group 3 (length 3):
[4, 5, 6]→ odd length, stays the same. - Group 4 (length 4):
[7, 8, 9, 10]→ even length, reversed to[10, 9, 8, 7].
Output: [1, 3, 2, 4, 5, 6, 10, 9, 8, 7]
Example 2
Input:
head = [1, 2, 3, 4, 5]
Explanation:
- Group 1 (length 1):
[1]→ odd length, stays the same. - Group 2 (length 2):
[2, 3]→ even length, reversed to[3, 2]. - Group 3 (remaining nodes, length ≤ 3):
[4, 5]→ since this last group has an even length (2), it gets reversed to[5, 4].
Output: [1, 3, 2, 5, 4]
Solution Idea is maintaining a groupLen, and iterating a node groupLen time also maintaing numNode value if its even we reverse else we update prev. we'll start by creating a prev pointing towards head. Grouplen initial value will be 2 since first group is always odd. we'll create a node pointer and numNodes count variable. we'll iterate node to groupLen and check numNodes is even or odd. if its even we'll reverse it.
function reverseEvenLengthGroups(head) {
let prev = head; // Node immediately before the current group
// The head doesn't need to be reversed since
// it's a group of one node, so starts with length 2
let groupLen = 2;
while (prev.next != null) {
let node = prev,
numNodes = 0;
for (let i = 0; i < groupLen; i++) {
if (node.next == null) break;
numNodes++;
node = node.next;
}
if (numNodes % 2)
// odd length
prev = node;
else {
// even length
let reverse = node.next;
let curr = prev.next,
currNext;
for (let j = 0; j < numNodes; j++) {
currNext = curr.next;
curr.next = reverse;
reverse = curr;
curr = currNext;
}
// updating the prev pointer after reversal of the even group
let prevNext = prev.next;
prev.next = node;
prev = prevNext;
}
// increment 1 by one and move to the next group
groupLen++;
}
return head;
}