Reverse a Linked List in groups of given size using Deque
Last Updated : 12 Jul, 2025
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 reverse a linked list in groups of size kusing a deque. For each group of size k, store nodes in the deque, then repeatedly swap the data of the first and last nodes by popping from both ends of the deque. Continue this process until all nodes are traversed.
Follow the steps below to solve the problem:
Initialize a deque(double-ended queue) of node type.
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 we reach to end of the 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)