Given a list, rotate the list to the right bykplaces, wherekis non-negative.
Example:
Given
1-
>
2-
>
3-
>
4-
>
5-
>
NULL
and
k
=
2
,
return
4-
>
5-
>
1-
>
2-
>
3-
>
NULL
.
tag: LinkedList
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return null;
ListNode fast = head;
int len = 1;
while (fast.next != null){
fast = fast.next;
len++;
}
fast.next = head;
k = k % len;
int lenlen = len - k;
ListNode slow = fast;
while (lenlen > 0){
slow = slow.next;
lenlen--;
}
ListNode ans = slow.next;
slow.next = null;
return ans;
}
}