链表向右移动k位。先成环,然后在len-k处打断。遍历两遍,第一遍找到尾指针,第二遍找到第len-k个节点,将循环链表打断
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head==NULL) return head;
ListNode* p=head;
int len=1;
while(p->next){
p=p->next;
len++;
}
p->next=head;
k=k%len;
int tmp=len-k;
p=head;
ListNode* pre=NULL;
while(tmp--){
pre=p;
p=p->next;
}
pre->next=NULL;
return p;
}
};