Skip to content

Commit 6d6cf86

Browse files
refactor:RotateSinglyLinkedLists
1 parent 0bd86b3 commit 6d6cf86

File tree

1 file changed

+35
-16
lines changed

1 file changed

+35
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,52 @@
11
package com.thealgorithms.datastructures.lists;
22

33
/**
4-
* Rotate a list
5-
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
4+
* Rotate a singly linked list
5+
*
66
*/
77

88
public class RotateSinglyLinkedLists {
9+
910
public Node rotateRight(Node head, int k) {
1011
if (head == null || head.next == null || k == 0) {
1112
return head;
1213
}
1314

14-
Node curr = head;
15-
int len = 1;
16-
while (curr.next != null) {
17-
curr = curr.next;
18-
len++;
15+
int length = getLength(head);
16+
k = k % length;
17+
if (k == 0) {
18+
return head;
1919
}
2020

21-
curr.next = head;
22-
k = k % len;
23-
k = len - k;
24-
while (k > 0) {
25-
curr = curr.next;
26-
k--;
27-
}
21+
Node last = getLastNode(head);
22+
last.next = head;
2823

29-
head = curr.next;
30-
curr.next = null;
24+
int stepsToNewHead = length - k;
25+
Node newLast = head;
26+
while (stepsToNewHead > 1) {
27+
newLast = newLast.next;
28+
stepsToNewHead--;
29+
}
30+
head = newLast.next;
31+
newLast.next = null;
3132
return head;
3233
}
34+
35+
private int getLength(Node head) {
36+
int length = 0;
37+
Node current = head;
38+
while (current != null) {
39+
length++;
40+
current = current.next;
41+
}
42+
return length;
43+
}
44+
45+
private Node getLastNode(Node head) {
46+
Node last = head;
47+
while (last.next != null) {
48+
last = last.next;
49+
}
50+
return last;
51+
}
3352
}

0 commit comments

Comments
 (0)