VOOZH about

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

⇱ Reverse a singly Linked List in groups of given size (Recursive Approach) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse a singly Linked List in groups of given size (Recursive Approach)

Last Updated : 23 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.

Example:

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 the first k nodes of the list and update the head of the list to the new head of this reversed segment. Then, connect the tail of this reversed segment to the result of recursively reversing the remaining portion of the list.

Follow the steps below to solve the problem:

  • If the list is empty, return the head.
  • Reverse the first k nodes using the reverseKNodes() function and update the new Head with the reversed list head.
  • Connect the tail of the reversed group to the result of recursively reversing the remaining list using the reverseKGroup() function.
  • Update next pointers during the reversal.
  • At last, return the new Head of the reversed list from the first group.

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 linked list.
Auxiliary Space: O(n / k)

Related articles:

Comment
Article Tags: