Add Rotate a Linkedlist (#4345)

This commit is contained in:
Bama Charan Chhandogi
2023-09-03 01:02:28 +05:30
committed by GitHub
parent a96ad84fac
commit 09950d6097
2 changed files with 105 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package com.thealgorithms.datastructures.lists;
/**
* Rotate a list
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public class RotateSinglyLinkedLists {
public Node rotateRight(Node head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
Node curr = head;
int len = 1;
while (curr.next != null) {
curr = curr.next;
len++;
}
curr.next = head;
k = k % len;
k = len - k;
while (k > 0) {
curr = curr.next;
k--;
}
head = curr.next;
curr.next = null;
return head;
}
}