代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(k==0||head==null||head.next==null)return head;
ListNode newHead = head;
ListNode cur = head;
ListNode end = head;
ListNode newEnd = head;
int n=1;
while(cur.next!=null){
n++;
cur = cur.next;
end = cur;
}
cur = head;
k%=n;
if(k==0)return head;
int i=0;
for(;i<n-k;i++){
newEnd = newHead;
newHead = cur.next;
cur = cur.next;
}
newEnd.next = null;
end.next = head;
return newHead;
}
}