Reverse a Linked List in groups of given size using Stack
Last Updated : 12 Sep, 2024
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed.
Examples:
Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 2 Output: head: 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL Explanation : Linked List is reversed in a group of size k = 2.
The idea is to use a Stack to store the nodes of the given linked list. Firstly, push the k nodes of the linked list into the stack. Now, pop the nodes one by one and keep track of the previously popped node. Point the next pointer of the prev node to the top element of the stack. Repeat this process, until we reach end of linked list.
Below is the implementation of the above approach:
Output
3 2 1 6 5 4
Time Complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(k)