mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Add Rotate a Linkedlist (#4345)
This commit is contained in:

committed by
GitHub

parent
a96ad84fac
commit
09950d6097
@ -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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user