Reverse a Linked List in groups of given size ‘K’

Objective: Given a linked list and integer ‘k’, write an algorithm to reverse the linked list in groups of size ‘k’.

Example:

Reverse a Linked List in groups of given size 'K' Example

Reverse a Linked List in groups of given size ‘K’ Example

Approach:

  • Earlier we have seen how to reverse a linked list, solution for reverse the linked list in groups of size will be extension of this solution.
  • Reverse first ‘k’ nodes of the linked list, the kth node will be a new head, return it.
  • Make a recursive call to rest of the list and attach it to the last node.(See the picture below)
Reverse a Linked List in groups of given size 'K'

Reverse a Linked List in groups of given size ‘K’

Complete Code:


Output:

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

  • Mukul Latiyan

    Hi, this code wont work, if say i have a linked list like 1->2->3->4->5 ans i want to reverse in group of 3 nodes then it will return 3->2->1->5->4 which is not correct. Can you suggest me another approach where we get 3->2->1->4->5 only.Thanks.

%d bloggers like this: