Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
代码语言:javascript复制 public ListNode rotateRight(ListNode head, int k) {
if (head == null)
return null;
int len = 1;
ListNode tail = head;
while (tail.next != null) {
len ;
tail = tail.next;
}
tail.next = head; // cycle
k %= len;
for (int i = 1; i < len - k; i ) {
head = head.next;
}
try {
return head.next;
} finally {
head.next = null; // cut
}
}