class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null || k==0) {
return head;
}
ListNode cur = head;//假节点指头
ListNode tail = null;//尾
int length = 1;
while(cur.next != null) {
cur = cur.next;
length++;
}//求长度
int num = length-(k%length);
tail = cur;//指尾
cur.next = head;//改循环链表
cur = head;
for(int i=0;i<num;i++) {
cur = cur.next;
tail = tail.next;
}
tail.next = null;//改回单链表
return cur;//返回头
}
}
本题说是循环旋转,但其实是将尾部向前数第K个元素作为头,原来的头接到原来的尾上,这应该也是一种更好的思路