VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-a-singly-linked-list-in-groups-of-given-size-set-3/

⇱ Reverse a Linked List in groups of given size using Deque - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

👁 Reverse-a-Linked-List-in-groups-of-given-size-1


Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 4 
Output: head:  4 -> 3 -> 2 -> 1 -> 6 -> 5 -> NULL
Explanation : Linked List is reversed in a group of size k = 4.

👁 Reverse-a-Linked-List-in-groups-of-given-size-2

Approach:

The idea is to reverse a linked list in groups of size k using 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)

Related articles:

Comment
Article Tags: