Given a singly linked list and an integer K, the task is to reverse every K nodes of the given linked list.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL, K = 3
Output: 3 2 1 6 5 4 8 7
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL, K = 5
Output: 5 4 3 2 1 8 7 6
- Create a deque.
- Store the address of the first k nodes in the deque.
- Pop first and the last value from the deque and swap the data values at those addresses.
- Repeat step 3 till the deque is not empty.
- Repeat step 2 for the next k nodes and till the end of the linked list is not reached.
Below is the implementation of the above approach:
Given linked list 1 2 3 4 5 6 7 8 9 10 K=2 Reversed Linked list 2 1 4 3 6 5 8 7 10 9
- Reverse a Linked List in groups of given size | Set 1
- Reverse a Linked List in groups of given size | Set 2
- Reverse a doubly linked list in groups of given size
- Reverse a Linked List in groups of given size (Iterative Approach)
- Reverse alternate K nodes in a Singly Linked List
- C Program to reverse each node value in Singly Linked List
- Reverse alternate K nodes in a Singly Linked List - Iterative Solution
- Reverse a Linked List according to its Size
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Sum of the nodes of a Singly Linked List
- QuickSort on Singly Linked List
- Circular Singly Linked List | Insertion
- Alternating split of a given Singly Linked List | Set 1
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.