VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-a-linked-list-in-groups-of-given-size-iterative-approach/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 6 Nov, 2025

Given a head of linked list and an integer k, reverse the list in groups of size k. If the total number of nodes is not a multiple of k, the remaining nodes at the end should also be treated as a group and reversed.

Examples:

Input: k = 2 

πŸ‘ t1

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

πŸ‘ t2

Input: k = 4 

πŸ‘ t1

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

πŸ‘ 4-

[Approach] Iterative K-Group Reversal

To reverse a linked list in groups of size k, the goal is to traverse the list in segments of k nodes and reverse each group individually. After reversing each group, we connect it to the previous group by updating the tail pointer. This will continues until the entire list is traversed, and we return the new head of the reversed list.

Step by Step Approach:

  • Initialize pointers:
    => Set curr to the head of the list to start traversing.
    => Set newHead to NULL to track the new head after the first group reversal.
    => Set tail to NULL to connect the previous group to the current reversed group.
  • Traverse the list in groups of k:
    => For each group of k nodes, set groupHead to curr.
    => Reverse the nodes in the group by updating the next pointers, using prev and nextNode.
  • Connect the reversed group to the previous one:
    => After reversing,if tail is not nullptr, connect the previous group's end to the current reversed group’s head.
    => Update tail to point to the last node of the current group.
  • Repeat the process until all nodes in the list are processed, and return newHead, which points to the head of the fully reversed list

Illustrations:



Output
3 -> 2 -> 1 -> 5 -> 4

Related articles:

Comment
Article Tags:
Article Tags: