Add reverse k group in LinkedList algorithm (#4532)

This commit is contained in:
Bama Charan Chhandogi
2023-10-03 12:13:49 +05:30
committed by GitHub
parent 6283572637
commit 536978919d
2 changed files with 117 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package com.thealgorithms.datastructures.lists;
/**
* Reverse K Group LinkedList (https://www.topcoder.com/thrive/articles/reverse-node-in-k-group)
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public class ReverseKGroup {
public int length(Node head) {
Node curr = head;
int count = 0;
while (curr != null) {
curr = curr.next;
count++;
}
return count;
}
// reverse function
public Node reverse(Node head, int count, int k) {
if (count < k) {
return head;
}
Node prev = null;
int count1 = 0;
Node curr = head;
Node Next = null;
while (curr != null && count1 < k) {
Next = curr.next;
curr.next = prev;
prev = curr;
curr = Next;
count1++;
}
if (Next != null) {
head.next = reverse(Next, count - k, k);
}
return prev;
}
public Node reverseKGroup(Node head, int k) {
int count = length(head);
Node ans = reverse(head, count, k);
return ans;
}
}