-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
60 lines (50 loc) · 1.32 KB
/
Solution.java
File metadata and controls
60 lines (50 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k < 0)
return null;
k %= getLength(head);
ListNode newHead = head;
ListNode fast = head;
ListNode slow = head;
int currIndex = 0;
while (fast != null && currIndex < k) {
fast = fast.next;
currIndex++;
}
if (fast == null || currIndex < k) {
return head;
}
ListNode prevSlow = slow;
ListNode prevFast = fast;
while (slow != null && fast != null) {
prevFast = fast;
fast = fast.next;
prevSlow = slow;
slow = slow.next;
}
if (slow == null) {
newHead = head;
} else {
newHead = slow;
prevFast.next = head;
prevSlow.next = null;
}
return newHead;
}
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
}