Reverse a Linked List in groups of a given size
Basics
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.
Here is the link: https://www.hrupin.com/2020/12/reverse-a-linked-list-in-groups-of-given-size-algorithm
Today we will talk about a case when we need to revert linked list nodes in groups of a given size.
Algorithm theory
Task definition
Given LinkedList:
5–>8–>13–>56–>12–>90–>53–>23–12–>NULL
Given group size: 3
We need split linked list into groups and reverse the nodes.
The result linked list must be like this:
13–>8–>5–>90–>12–>56–>12–>23–53–>NULL
Solution
- 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
Sample code
Below you will get a link to GitHub repo with Kotlin, Java, and Python source code
0 Comments