-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrotate-list.java
38 lines (36 loc) · 1.03 KB
/
rotate-list.java
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
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
// find old tail node and list length
ListNode tail = head;
int len = 1;
while (tail.next != null) {
tail = tail.next;
len++;
}
if (k == len || k % len == 0) { // no need to rotate
return head;
}
ListNode newTail = findLastK(head, k % len + 1);
ListNode newHead = newTail.next;
tail.next = head;
newTail.next = null;
return newHead;
}
private ListNode findLastK(ListNode head, int k) {
ListNode slow = head;
ListNode fast = head;
// we can guarantee fast will not be null
for (int i = 0; i < k; i++) {
fast = fast.next;
}
// fast stop at null, slow stop at last K node
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}