This post is completed by 1 user
|
Add to List |
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](/static/media/algorithms/2016/01/Reverse-a-Linked-List-in-groups-of-given-size-K-Example.png)
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'](/static/media/algorithms/2016/01/Reverse-a-Linked-List-in-groups-of-given-size-K-1.png)
Output:
->3->2->1->6->5->4->8->7