给定一个列表,把列表向右旋转 k 个位置,k 非负。
例如:给定列表 1->2->3->4->5->NULL 和 k = 2,返回 4->5->1->2->3->NULL。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k <= 0) {
return head;
}
int length = 1;
ListNode tail = head;
while (tail.next != null) {
length++;
tail = tail.next;
}
k = k % length;
if (k == 0) {
return head;
}
ListNode p = head;
int i = length - k - 1;
while (i > 0) {
p = p.next;
i--;
}
tail.next = head;
head = p.next;
p.next = null;
return head;
}
}