• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
August 16, 2024 |1.8K Views

Reverse a Linked List in groups of given size | Set 1

Description
Discussion

Given a linked list, write a function to reverse every k nodes (where k is an input to the function). 

Algorithm: reverse(head, k)

Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev. See this post for reversing a linked list.


head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )


Return prev ( prev becomes the new head of the list (see the diagrams of an iterative method of this post )

 

Related Article : https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/