题目:
分析:
以1->2->3->4->5 k=2为例
将链表首尾相连
将head和end依次向后移n-k个位置 n为原链表长度
在这里需要移3个位置
再将end 的next改为null
这道题就算完成了
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
ListNode end=head;
//当链表为空时,直接返回
if(head==null) return head;
int n=1;
while(end.next!=null){
n++;
end=end.next;
}
k=k%n;
//当k的余数为0时,链表不需要移动,直接返回head
if(k==0)return head;
end.next=head;
for(int i=0;i<n-k;i++){
head=head.next;
end=end.next;
}
end.next=null;
return head;
}
}