Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
解題思路:
雙指針(tail,pre)找到鏈表的尾部和總長度,使用pre走 (len-k%(len)-1) 長度到達要修改的尾部點進行修改
/**
* 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 *tail,*pre;
tail=pre=head;
int len=1;
while(tail->next!=NULL) //找到尾部
{
tail=tail->next;
len++;
}
int i=len-(k%(len))-1; //考慮k數據的過大
while(i>0)
{
i--;
pre=pre->next;
}
tail->next=head;
head=pre->next;
pre->next=NULL;
return head;
}
};