Reverse LinkedList in K nodes group - Data Structure Linked List
I this problem we have to reverse the nodes of the Linkedlist k at a time and leave the remaining nodes if number of nodes is not a multiple of k. For example If we have a LinkedList having 11 nodes and we are asked to reverse it for k=3 nodes at a time, we will reverse first 3 elements then next 3 elements and then again next 3 elements and leave the last 2 elements as it is.
Check below diagram to understand the example -
Check below diagram to understand the example -
Approach : First we will find the size of the LinkedList and divide it by k to know the number of groups which needs to be reversed. We will write a recursive method which will reverse the group of k nodes and return the last node of the reversed group. We will call this recursive function for all the groups which needs to be revesed.
In above example list size is 11 and value of k is 3 so we will get total 11/3 3 groups which needs to be reversed leaving the last 2 ekements unchanged.
To revese the pointed of a node we will use simple iterative approach inside the recursive method using 3 pointers current, prev, and next.
In above example list size is 11 and value of k is 3 so we will get total 11/3 3 groups which needs to be reversed leaving the last 2 ekements unchanged.
To revese the pointed of a node we will use simple iterative approach inside the recursive method using 3 pointers current, prev, and next.
Code :
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
*
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int grp = getSize(head)/k;
head = reverse(head, k, grp);
return head;
}
public int getSize(ListNode head){
ListNode node = head;
int size = 0;
while(node != null){
size++;
node = node.next;
}
return size;
}
public ListNode reverse(ListNode node, int k, int grp) {
if(grp <= 0)
return node;
ListNode current = node;
ListNode prev = null;
ListNode next = null;
int n = 1;
while(current != null && n <= k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
n++;
}
grp--;
node.next = reverse(next, k, grp);
return prev;
}
}
Main method to run the code :
public static void main(String[] args) {
int k = 3;
JKLinkedList list = new JKLinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
list.add(10);
list.add(11);
Solution solution = new Solution();
list.head = solution.reverseKGroup(list.head, k);
}
In above code JKLinkedList is a custom implementation for LinkedList, Its add method adds the element at the end of the current list.
This custom class implementation has not been provided in this article, for details about implementing the custom LinkedList you can check the dedicated article.
The implementation code has beed tested for different data sets.
Comments
Post a Comment