这题做了很久,有个地方卡了很久
大致的想法是先把链表连成环,同时记录链表的长度count,再进行平移,这里设置了两个指针,一个在前,一个在后,也就是快慢指针,一开始慢指针在原链表的末尾,快指针在头,对快指针进行平移,慢指针紧跟其后,平移count-k个单位(关于这个平移还有一些疑问,想通后进行补充),再令慢指针的next为NULL
/**
* 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||k==0) return head;
ListNode *cur=head;
ListNode *p=head;
int count=0;
while(cur!=NULL){
p=cur;
cur=cur->next;
count++;
}
p->next=head;
cur=head;
if(k>count) k=k%count;
while(count-k>0){
p=cur;
cur=cur->next;
count--;
}
p->next=NULL;
return cur;
}
};