题目:
分析:只提醒一点,应该先取余。
代码:
/**
* 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||head->next==NULL) return head;
ListNode* head2=head;
int len=1;
while(head2->next!=NULL)
{
head2=head2->next;
len++;
}
k=k%len;
if(k==0) return head;
//head2此时所在的位置就是整个链表的最后一个位置。
head2->next=head;
for(int i=1;i<len-k;i++)
{
head=head->next;
}
head2=head->next;
head->next=NULL;
return head2;
}
};