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.
需要考虑k大于链表长度,主流的方法是将链表成环然后找到位置然后断环。
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(head == NULL ){return head;}
int nsize =1;
ListNode *p = head;
ListNode *q = head;
while(p->next)
{
p = p->next;
nsize ++;
}
p->next = head;
for(int i=0;i<nsize-k%nsize-1;i++)
{
q = q->next;
}
p = q->next;
q->next = NULL;
return p;
}
};
257

被折叠的 条评论
为什么被折叠?



