Given a linked list and an integer K, the task is to reverse every alternate K nodes.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 3
Output: 3 2 1 4 5 6 9 8 7
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 5
Output: 5 4 3 2 1 6 7 8 9
Approach: We have already discussed a recursive solution here. In this post, we will discuss an iterative solution to the above problem. While traversing we process 2k nodes in one iteration and keep track of the first and last node of the group of k-nodes in the given linked list using the join and tail pointer. After reversing the k nodes of the linked list, we join the last node of the reversed list, pointed by the tail pointer, with the first node of the original list, pointed by the join pointer. We then move the current pointer until we skip the next k nodes.
The tail now becomes the last node of the normal list (which is pointed by the updated tail pointer) and join points to the first of the reversed list and they are then joined. We repeat this process until all the nodes are processed in the same way.
Below is the implementation of the above approach:
Given linked list 1 2 3 4 5 6 7 8 9 10 Modified Linked list 3 2 1 4 5 6 9 8 7 10
Time Complexity: O(n)
Space Complexity: O(1)
- Reverse alternate K nodes in a Singly Linked List
- Alternate Odd and Even Nodes in a Singly Linked List
- Print the alternate nodes of linked list (Iterative Method)
- Given a linked list, reverse alternate nodes and append at the end
- Print the last k nodes of the linked list in reverse order | Iterative Approaches
- C Program to reverse each node value in Singly Linked List
- Sum of the nodes of a Singly Linked List
- Product of the nodes of a Singly Linked List
- Sum of the alternate nodes of linked list
- Count of Prime Nodes of a Singly Linked List
- Delete all Prime Nodes from a Singly Linked List
- Delete all Non-Prime Nodes from a Singly Linked List
- Sum and Product of the nodes of a Singly Linked List which are divisible by K
- Find the common nodes in two singly linked list
- Sum and Product of all Prime Nodes of a Singly Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.