原理在linked list cycle 中已经叙述过了 这里不再叙述
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast=head;
ListNode *slow=head;
if(!head)
return false;
bool hascycle=false;
while(slow&&fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
hascycle=true;
break;
}
}
if(!hascycle)
return NULL;
else
{
ListNode *temp=head;
while(1)
{
if(temp==slow)
break;
temp=temp->next;
slow=slow->next;
}
return slow;
}
}
};