-
Notifications
You must be signed in to change notification settings - Fork 69
/
Rotate List
51 lines (45 loc) Β· 866 Bytes
/
Rotate List
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
class Solution
{
public ListNode rotateRight(ListNode head, int k)
{
int size = len(head);
if (size == 0) return null;
k %= size;
if (k == 0) return head;
ListNode fast = head;
while (k!= 0)
{
k--;
fast = fast.next;
}
ListNode slow = head;
while (fast.next != null)
{
fast = fast.next;
slow = slow.next;
}
ListNode result = slow.next;
slow.next = null;
fast.next = head;
return result;
}
int len(ListNode head)
{
int count = 0;
while (head != null)
{
++count;
head = head.next;
}
return count;
}
}
Input
head =
[1,2,3,4,5]
k =
2
Output
[4,5,1,2,3]
Expected
[4,5,1,2,3]