061.Rotate List

Solution 1: accepted 16ms

A common brute force solution

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
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
ListNode dummy = head;
ListNode tail = null;
int length = 0;
while (dummy != null) {
tail = dummy;
dummy = dummy.next;
length++;
}
k = k % length;
dummy = head;
for (int i = 1; i < length - k; i++) {
dummy = dummy.next;
}
ListNode newHead = head;
if (dummy.next != null) {
newHead = dummy.next;
dummy.next = null;
tail.next = head;
}
return newHead;
}