Given a linked list, reverse every adjacent group of k nodes where k is a given positive integer.

For example,

Input List: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> null
 
 
For k = 3,
Output: 3 —> 2 —> 1 —> 6 —> 5 —> 4 —> 8 —> 7 —> null
 
 
For k = 2,
Output: 2 —> 1 —> 4 —> 3 —> 6 —> 5 —> 8 —> 7 —> null
 
 
For k = 1,
Output: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> null
 
 
For k >= 8,
Output: 8 —> 7 —> 6 —> 5 —> 4 —> 3 —> 2 —> 1 —> null

Practice this problem

The idea is to consider every group of k nodes and recursively reverse them one at a time. Special care has to be taken while linking reversed groups with each other.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

3 —> 2 —> 1 —> 6 —> 5 —> 4 —> 8 —> 7 —> NULL

Java


Download  Run Code

Output:

3 —> 2 —> 1 —> 6 —> 5 —> 4 —> 8 —> 7 —> null

Python


Download  Run Code

Output:

3 —> 2 —> 1 —> 6 —> 5 —> 4 —> 8 —> 7 —> None

The above solution returns the head pointer from the function. Alternatively, we can pass a pointer (reference) to the head node to the reverseInGroups() function and avoid updating the head pointer insider the main() function.

Following is the C program that demonstrates it:

C


Download  Run Code

The time complexity of the above solution is O(n), where n is the length of the linked list. The auxiliary space required by the program for the call stack is proportional to the lists’ length.
 

 
Exercise: Modify the solution to reverse every alternate group of k nodes.