File tree 1 file changed +14
-32
lines changed
src/main/java/com/thealgorithms/datastructures/lists 1 file changed +14
-32
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 singly linked list
5
- *
4
+ * Rotate a singly linked list to the right
6
5
*/
7
-
8
6
public class RotateSinglyLinkedLists {
9
-
10
7
public Node rotateRight (Node head , int k ) {
11
8
if (head == null || head .next == null || k == 0 ) {
12
9
return head ;
13
10
}
14
11
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
+
16
19
k = k % length ;
17
20
if (k == 0 ) {
18
21
return head ;
19
22
}
20
23
21
- Node last = getLastNode (head );
22
- last .next = head ;
23
-
24
- int stepsToNewHead = length - k ;
25
24
Node newLast = head ;
26
- while ( stepsToNewHead > 1 ) {
25
+ for ( int i = 0 ; i < length - k - 1 ; i ++ ) {
27
26
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 ;
41
27
}
42
- return length ;
43
- }
44
28
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 ;
51
33
}
52
- }
34
+ }
You can’t perform that action at this time.
0 commit comments