...

/

Reverse Nodes In Even Length Groups

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 (1,2,3,4...)(1,2,3,4...).

In other words:

  • The 1st1^{st} node is assigned to the first group.

  • The 2nd2^{nd} and 3rd3^{rd} nodes are assigned to the second group.

  • The 4th4^{th}, 5th5^{th}, and 6th6^{th} 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:

  • 11 \leq Number of nodes 500\leq 500

  • 00 \leq ListNode.Value 103\leq 10^3

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

1.

What is the output if the following linked list is provided as input?

4 → 3 → 0 → 5 → 1 → 2 → 7 → 8 → 6

A.

3 → 4 → 2 → 1 → 5 → 0 → 7 → 8 → 6

B.

3 → 4 → 5 → 0 → 2 → 1 → 8 → 7 → 6

C.

4 → 0 → 3 → 5 → 1 → 2 → 8 → 7 → 6

D.

4 → 0 → 3 → 5 → 1 → 2 → 7 → 8 → 6


1 / 3

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.

Sequence - Vertical
Reverse Nodes in Even Length Groups

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

Go
usercode > Solution.go
// Definition for a Linked List node
// type ListNode struct {
// Val int
// Next *ListNode
// }
package main
import (. "golang-test-code/ds_v1/LinkedList")
func reverseEvenLengthGroups(head *ListNode) {
// Replace this placeholder return statement with your code
}
Reverse Nodes in Even Length Groups

Access this course and 1200+ top-rated courses and projects.