注意此题head节点不为空!!!head->va
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* rotateLinkedList(ListNode* head, int k) {
// write code here
if(k==0||head==nullptr){
return head;
}
int len=0;
ListNode *p=head;
while(p){
len++;
p=p->next;
}
k%=len;
int count=1;
int n=len-k-1;
p=head->next;
ListNode *pre=head;;
while(n--){
pre=pre->next;
p=p->next;
}
ListNode *tail;
tail=p;
while(count<k){
count++;
tail=tail->next;
}
tail->next=head;
pre->next=NULL;
return p;
}
};
l有值