题目:
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *pFast=head,*pSlow=head;
while(true){
if(!pFast||!pFast->next){
return NULL;
}
pFast=pFast->next->next;
pSlow=pSlow->next;
if(pFast==pSlow){
break;
}
}
pFast=head;
while(pSlow!=pFast){
pFast=pFast->next;
pSlow=pSlow->next;
}
return pFast;
}
我的思考:
因为昨天刚做了判断环是否存在的题目,这道题我的思路其实是用链表的整体长度减去环的长度;但是题解给出了更妙的解法:设a为环前链表长度,b为环长,f、s分别为快慢指针。双指针在第一次相遇时,f=2s,且f-s=nb。相遇之后,令其中一个指针回到head头结点,二者速度相等的跳动,则在这一轮f=s=a。也就得到了a的长度。其实第二轮的思想和求倒数第k个节点有些类似,不过双指针的题目都有很多共同之处,经验++!