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:
2 1 4 3 6 5 8 7 10 9
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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)
- 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
- 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
- Alternating split of a given Singly Linked List | Set 1
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Reverse a Linked List according to its Size
- Function to check if a singly linked list is palindrome
- QuickSort on Singly Linked List
- Select a Random Node from a Singly Linked List
- Circular Singly Linked List | Insertion
- Insertion Sort for Singly Linked List
- Recursive selection sort for singly linked list | Swapping node links
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.