Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->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) return head;
int len=1;
ListNode* tail=head,*newhead=head;
while(tail->next)
{
tail=tail->next;
len++;
}
tail->next=head;
if(k%=len)
{
for(auto i=0;i<len-k;i++) tail=tail->next;
}
newhead=tail->next;
tail->next=NULL ;
return newhead;
}
};