Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
题目要求,判断一个单链表中是否存在环,若存在返回环的起始节点,否则,返回NULL。
使用快慢指针的方法判断是否存在环,参见文章Linked List Cycle。
下面分析怎么寻找环的起始节点。
看下面一张模拟图,fast指针和slow指针相遇点为C,fast走过路程为a+b+c+b,slow走过路程为a+b。
fast指针走过的路程是slow指针走过路程的两倍,所以有等式: a+b+c+b=2(a+b),化简可得a=c;也就是说,起始节点A和相遇节点C距离环的起始节点B距离相同,有了这个条件,我们只要使用两个指针从A,C出发,以相等的速度前进,他们相遇处就是环的起始节点。
AC code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head)
{
if(head==NULL||head->next==NULL)
return NULL;
ListNode *fast=head,*slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
break;
}
if(fast==NULL||fast->next==NULL)
return NULL;
fast=head;
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}
return fast;
}
};