Close
Topic list
Reverse Alternate K nodes
EASY
10 mins
Topics (Covered in this problem)
Problem solved
Skill meter
-
-
Other topics
Problem solved
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Reverse Alternate K nodes

Contributed by
Ambuj verma
Easy
0/40
Avg time to solve 10 mins
Success Rate 90 %
Share

Problem Statement

You are given a Singly Linked List of integers and a positive integer 'K'. Modify the linked list by reversing every alternate 'K' nodes of the linked list.

``````A singly linked list is a type of linked list that is unidirectional, that is, it can be traversed in only one direction from head to the last node (tail).
``````
Note:
``````If the number of nodes in the list or in the last group is less than 'K', just reverse the remaining nodes.
``````
Example:
``````Linked list: 5 6 7 8 9 10 11 12
K: 3

Output: 7 6 5 8 9 10 12 11

We reverse the first 'K' (3) nodes and then skip the next 'K'(3) nodes. Now, since the number of nodes remaining in the list (2) is less than 'K', we just reverse the remaining nodes (11 and 12).
``````
Note:
``````You need to reverse the first 'K' nodes and then skip the 'K' nodes and so on. 5 6 7 10 9 8 11 12 is not the correct answer for the given linked list.
``````
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
``````1
1 2 3 4 5 6 7 -1
2
``````
Sample Output 1:
``````2 1 3 4 6 5 7 -1
``````
Explanation of sample input 1:
``````In the given linked list, we have to reverse the first two nodes, then skip two nodes, and so on… until all the nodes are processed in the same way.
The modified linked list after the above process is 2 1 3 4 6 5 7 -1
``````
Sample Input 2:
``````2
5 10 -6 4 7 -1
3
10 20 30 40 50 -1
1
``````
Sample Output 2:
``````-6 10 5 4 7 -1
10 20 30 40 50 -1
``````
Auto
Console