Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,33 +1,52 @@
package com.thealgorithms.datastructures.lists;

/**
* Rotate a list
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
* Rotate a singly linked list
*
*/

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++;
int length = getLength(head);
k = k % length;
if (k == 0) {
return head;
}

curr.next = head;
k = k % len;
k = len - k;
while (k > 0) {
curr = curr.next;
k--;
}
Node last = getLastNode(head);
last.next = head;

head = curr.next;
curr.next = null;
int stepsToNewHead = length - k;
Node newLast = head;
while (stepsToNewHead > 1) {
newLast = newLast.next;
stepsToNewHead--;
}
head = newLast.next;
newLast.next = null;
return head;
}

private int getLength(Node head) {
int length = 0;
Node current = head;
while (current != null) {
length++;
current = current.next;
}
return length;
}

private Node getLastNode(Node head) {
Node last = head;
while (last.next != null) {
last = last.next;
}
return last;
}
}
Loading