Skip to content

Commit 76b490c

Browse files
refactor:RotateSinglyLinkedLists.java making minute changes
1 parent 6d6cf86 commit 76b490c

File tree

1 file changed

+14
-32
lines changed

1 file changed

+14
-32
lines changed
Lines changed: 14 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,34 @@
11
package com.thealgorithms.datastructures.lists;
22

33
/**
4-
* Rotate a singly linked list
5-
*
4+
* Rotate a singly linked list to the right
65
*/
7-
86
public class RotateSinglyLinkedLists {
9-
107
public Node rotateRight(Node head, int k) {
118
if (head == null || head.next == null || k == 0) {
129
return head;
1310
}
1411

15-
int length = getLength(head);
12+
Node last = head;
13+
int length = 1;
14+
while (last.next != null) {
15+
last = last.next;
16+
length++;
17+
}
18+
1619
k = k % length;
1720
if (k == 0) {
1821
return head;
1922
}
2023

21-
Node last = getLastNode(head);
22-
last.next = head;
23-
24-
int stepsToNewHead = length - k;
2524
Node newLast = head;
26-
while (stepsToNewHead > 1) {
25+
for (int i = 0; i < length - k - 1; i++) {
2726
newLast = newLast.next;
28-
stepsToNewHead--;
29-
}
30-
head = newLast.next;
31-
newLast.next = null;
32-
return head;
33-
}
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;
4127
}
42-
return length;
43-
}
4428

45-
private Node getLastNode(Node head) {
46-
Node last = head;
47-
while (last.next != null) {
48-
last = last.next;
49-
}
50-
return last;
29+
Node newHead = newLast.next;
30+
newLast.next = null;
31+
last.next = head;
32+
return newHead;
5133
}
52-
}
34+
}

0 commit comments

Comments
 (0)