-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathRotateList.java
45 lines (40 loc) · 1.23 KB
/
RotateList.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
39
40
41
42
43
44
45
// https://leetcode.com/problems/rotate-list
// T: O(N)
// S: O(1)
public class RotateList {
public ListNode rotateRight(ListNode head, int k) {
final int length = getLength(head);
if (length == 0) return head;
final int rotations = k % length;
if (rotations == 0) return head;
final ListNode last = getLastNode(head);
final ListNode cutoffNode = getCutoffNode(head, rotations, length);
final ListNode newHead = cutoffNode.next;
last.next = head;
cutoffNode.next = null;
return newHead;
}
private int getLength(ListNode head) {
int length = 0;
ListNode current = head;
while (current != null) {
current = current.next;
length++;
}
return length;
}
private ListNode getLastNode(ListNode head) {
ListNode current = head;
while (current.next != null) {
current = current.next;
}
return current;
}
private ListNode getCutoffNode(ListNode head, int rotations, int length) {
ListNode current = head;
for (int i = 0 ; i < length - rotations - 1 ; i++) {
current = current.next;
}
return current;
}
}