首先上题目:
题目中给定了一个K(旋转次数),输入一个链表,要求将链表从末尾旋转k次。那么难点在于:
- 怎样快速找到链表的末尾
- 怎样调整头指针
对于第二个问题,只需给定一个临时的指针变量,待指到最后一个节点时,将最后一个节点反指回头结点,再将头结点指到临时指针的位置。
对于第一个问题,可以考虑连续两次移动指针的方式来找到表尾的方式。
(如下图)
最后,一个非常狗血的问题:测试样例有k值上万的情况。注意到旋转的次数超过链表的长度会出现循环。所以可以对K求余来实现。
代码:
int length(ListNode* a)
{
int fin = 0;
for (ListNode* temp = a; temp; temp = temp->next)
{
fin++;
}
return fin;
}
ListNode* findthelast(ListNode* head, ListNode* tar)
{
for(ListNode* temp=head;temp;temp=temp->next->next)
{
if(temp->next==tar)
return temp;
else if(temp->next->next==tar)
return temp->next;
}
return head;
}
ListNode* rotateRight(ListNode* head, int k) {
if(head&&head->next)
{
ListNode* last;
int sizes = length(head);
for(int i=0;i<k%sizes;i++)
{
last=findthelast(head,NULL);
ListNode* pre=findthelast(head,last);
pre->next=last->next;
last->next=head;
head=last;
}
return head;
}
else
return head;
}