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

For example,

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

Practice this problem

1. Iterative Solution

The idea is to traverse the linked list and consider every group of 2×k nodes at a time. In a single iteration of the loop, reverse the first k nodes and skip the next k nodes. Special care has to be taken while linking reversed groups with the rest of the list.

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

C++


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> nullptr
Resultant linked list: 2 —> 1 —> 3 —> 4 —> 6 —> 5 —> 7 —> 8 —> 10 —> 9 —> nullptr

Java


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> null
Resultant linked list: 2 —> 1 —> 3 —> 4 —> 6 —> 5 —> 7 —> 8 —> 10 —> 9 —> null

Python


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> None
Resultant linked list: 2 —> 1 —> 3 —> 4 —> 6 —> 5 —> 7 —> 8 —> 10 —> 9 —> None

The time complexity of the above iterative solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.

2. Recursive Solution

The recursive solution is similar to the iterative solution where we reverse the first k nodes and skip the next k nodes. But here, recursively call for the rest of the list.

The recursive implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> nullptr
Resultant linked list: 2 —> 1 —> 3 —> 4 —> 6 —> 5 —> 7 —> 8 —> 10 —> 9 —> nullptr

Java


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> null
Resultant linked list: 2 —> 1 —> 3 —> 4 —> 6 —> 5 —> 7 —> 8 —> 10 —> 9 —> null

Python


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> None
Resultant linked list: 2 —> 1 —> 3 —> 4 —> 6 —> 5 —> 7 —> 8 —> 10 —> 9 —> None

The time complexity of the above recursive 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.

 
Related Post:

Reverse every group of k nodes in a linked list