This post is completed by 1 user

  • 0
Add to List
Medium

186. 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'

Output:

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