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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Reverse a Linked List in groups of given size | Set 2
- Reverse a Linked List in groups of given size | Set 1
- Reverse a doubly linked list in groups of given size
- Reverse a Linked List in groups of given size (Iterative Approach)
- C Program to reverse each node value in Singly Linked List
- Reverse alternate K nodes in a Singly Linked List
- Reverse alternate K nodes in a Singly Linked List - Iterative Solution
- Reverse a Linked List according to its Size
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- Convert Singly Linked List to XOR Linked List
- Sum of the nodes of a Singly Linked List
- QuickSort on Singly Linked List
- Convert a String to a Singly Linked List
- Convert a Singly Linked List to an array
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.