/**
* 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) {
return head;
}
int len = getLength(head);
k = k % len;
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
for (int i = 0; i < k; i++) {
head = head.next;
}
ListNode tail = dummy;
while (head.next != null) {
tail = tail.next;
head = head.next;
}
head.next = dummy.next;
dummy.next = tail.next;
tail.next = null;
return dummy.next;
}
private int getLength(ListNode head) {
int len = 0;
while (head != null) {
head = head.next;
len++;
}
return len;
}
}