VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-given-linked-list-in-groups-of-specific-given-sizes/

⇱ Reverse given Linked List in groups of specific given sizes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse given Linked List in groups of specific given sizes

Last Updated : 23 Jul, 2025

Given the linked list and an array arr[] of size N, the task is to reverse every arr[i] nodes of the list at a time (0 ≤ i < N).

Note: If the number of nodes in the list is greater than the sum of array, then the remaining nodes will remain as it is.

Examples:

Input: head = 1->2->3->4->5->6->7->8->9, arr[] = {2, 3, 3}
Output: 2->1->5->4->3->8->7->6->9
Explanation: The first group of size 2 is 1->2. Upon reversing it becomes 2->1.
The next group of size 3 is 3->4->5 which on reversing becomes 5->4->3.
The last group of size 3 is 6->7->8 which on reversing becomes 8->7->6.

Input: head = 6->8->7, arr[] = {1, 2}
Output: 6->7->8

Approach: The solution to the problem is based on the idea of selecting groups of nodes of arr[i] size and considering each sublist as an individual linked list and using the concept of reversing a linked list.

Follow the illustration below for a better understanding:

Illustration:

👁 Image
reverse(head, arr, n, index)

Follow the steps mentioned below to implement the idea:

  • Traverse through the array from i = 0 to N:
    • Reverse the sub-list of size arr[i].
      • While reversing the sub-list, for each node, interchange the pointers pointing to the next node and the previous node.
  • If the end of the array is reached, stop iteration and return the head pointer of the final list.

Below is the implementation of the above approach.


Output
2->1->5->4->3->8->7->6->9->

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment