Reverse Nodes In Even Length Groups
Try to solve the Reverse Nodes in Even Length Groups problem.
Statement
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
In other words:
The
node is assigned to the first group. The
and nodes are assigned to the second group. The
, , and 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 the last group.
Constraints:
Number of nodes ListNode.Value
Examples
You can understand the problem a little better with the help of the illustration below:
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:
Reverse Nodes in Even Length Groups
What is the output if the following linked list is provided as input?
4 → 3 → 0 → 5 → 1 → 2 → 7 → 8 → 6
3 → 4 → 2 → 1 → 5 → 0 → 7 → 8 → 6
3 → 4 → 5 → 0 → 2 → 1 → 8 → 7 → 6
4 → 0 → 3 → 5 → 1 → 2 → 8 → 7 → 6
4 → 0 → 3 → 5 → 1 → 2 → 7 → 8 → 6
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
// Definition for a Linked List node// type ListNode struct {// Val int// Next *ListNode// }package mainimport (. "golang-test-code/ds_v1/LinkedList")func reverseEvenLengthGroups(head *ListNode) {// Replace this placeholder return statement with your code}