File tree 1 file changed +35
-16
lines changed
src/main/java/com/thealgorithms/datastructures/lists
1 file changed +35
-16
lines changed Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .datastructures .lists ;
2
2
3
3
/**
4
- * Rotate a list
5
- * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
4
+ * Rotate a singly linked list
5
+ *
6
6
*/
7
7
8
8
public class RotateSinglyLinkedLists {
9
+
9
10
public Node rotateRight (Node head , int k ) {
10
11
if (head == null || head .next == null || k == 0 ) {
11
12
return head ;
12
13
}
13
14
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 ;
19
19
}
20
20
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 ;
28
23
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 ;
31
32
return head ;
32
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 ;
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
+ }
33
52
}
You can’t perform that action at this time.
0 commit comments