Rotate List
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.
需要注意的几点:
1)求链表长度的时候,千万注意是while(p->next),如果num初始值为1;
2)k有可能大于len,需要注意
3)构造了环形链表,然后再断开
/**
* 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(k==0||head==NULL) return head;
ListNode *p;
p=head;
int num=1;
while(p->next)
{
p=p->next;
num++;
}
p->next=head;
k=num-k%num;
for(int i=0;i<k;i++)
{
p=p->next;
}
head=p->next;
p->next=NULL;
return head;
}
};