/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k <= 0) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode ptr = dummy;
int length = 0;
while (ptr.next != null) {
length++;
ptr = ptr.next;
}
k = k % length;
if (k == 0) {
return head;
}
ListNode fast = dummy;
ListNode slow = dummy;
for (int i = 0; i < k; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
fast.next = dummy.next;
dummy.next = slow.next;
slow.next = null;
return dummy.next;
}
}