LeetCode61 Rotate List 解题报告
Given a list, rotate the list to the right by k places, where k is non-negative.
题目的意思是: 在一个列表中找到倒数第k个的节点,然后进行旋转,即将该节点作为头节点,将该节点前的节点连接到最好的节点。
例子:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
其中k没有指明是否大于等于链表长度(等于的话,即为链表末的下一个节点 NULL), 所以当k==链表长度,即从链表头开始重新计算,故可以得到倒数第k个节点必然是k”=k%len;
代码如下:
ListNode *rotateRight(ListNode *head, int k)
{
ListNode *result;
if(head==NULL)
{
return head;
}
if(head->next==NULL)
{
return head;
}
ListNode *first=head;
int len=1;
//求倒数第k个节点,让first先走k步,然后让first跟second 一起走,当first到链表末,second即为倒数第k+1个节点
while(--k>=0)
{
if(first->next!=NULL)
{
first=first->next;
len++;
}
else{
first=head;
k=k%len;
}
}
//当first 为头部的时候,即不用旋转,愿链表即是所求的链表
if(first==head)
return first;
ListNode *second=head;
while(first->next!=NULL)
{
first=first->next;
second=second->next;
}
//second->next 即为倒数第k个节点
result=second->next;
second->next=first->next;
first->next=head;
return result;
}