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,34 @@
package com.thealgorithms.datastructures.lists;

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

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++;
Node last = head;
int length = 1;
while (last.next != null) {
last = last.next;
length++;
}

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 newLast = head;
for (int i = 0; i < length - k - 1; i++) {
newLast = newLast.next;
}

head = curr.next;
curr.next = null;
return head;
Node newHead = newLast.next;
newLast.next = null;
last.next = head;
return newHead;
}
}
}
Loading