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:
int cnt=0;
int count=0;
void rotate(ListNode *head,ListNode *&p1,ListNode *&p2) //p1,p2将指向需要改变的结点
{
if(head==NULL)
{
if(count)
cnt%=count;
return ;
}
ListNode *t=head;
count++;
rotate(head->next,p1,p2);
if(head->next==NULL)
p2=head;
if(cnt==0)
{
p1=t;
cnt=-1;
return;
}
cnt--;
}
ListNode* rotateRight(ListNode* head, int k) {
cnt=k;
ListNode *p1=NULL,*p2=NULL;
rotate(head,p1,p2);
if(p1 && p2)
{
p2->next=head; //成环
head=p1->next;
p1->next=NULL; //新的尾结点
}
return head;
}
};