Reverse a Linked List in groups of a given size
In the previous post, we talked about reverse the entire LinkedList. You also can get info about what is it LinkedList and a high-level view of how it works.
Today we will talk about a case when we need to revert linked list nodes in groups of a given size.
Given group size: 3
We need split linked list into groups and reverse the nodes.
The result linked list must be like this:
- 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 the 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
Below you will get a link to GitHub repo with Kotlin, Java, and Python source code