Mid/SeniorLinked List
Reverse Nodes in Even Length Groups
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
1^stnode is assigned to the first group. - The
2^ndand the3^rdnodes are assigned to the second group. - The
4^th,5^th, and6^thnodes 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.
Example 1
[5] -> [2] -> [6] -> [3] -> [9] -> [1] -> [7] -> [3] -> [8] -> [4] -> null --- [5] -> [6] -> [2] -> [3] -> [9] -> [1] -> [4] -> [8] -> [3] -> [7] -> null
Input
head = [5,2,6,3,9,1,7,3,8,4]Output
[5,6,2,3,9,1,4,8,3,7]The first and third groups have odd lengths and are unchanged, while the second group
[2, 6] and last group [7, 3, 8, 4] have even lengths and are reversed.Example 2
[1] -> [1] -> [0] -> [6] -> null --- [1] -> [0] -> [1] -> [6] -> null
Input
head = [1,1,0,6]Output
[1,0,1,6]The first and last groups have length 1 and are unchanged, while the second group
[1, 0] has even length and is reversed.Constraints
- The number of nodes in the list is in the range
[1, 10^5]. 0 <= Node.val <= 10^5