环一圈后位置不变所以可以看做分别以x 和 z为起点相遇在x处 即是入口
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *fast;
struct ListNode *slow;
struct ListNode *bIndex;
struct ListNode *mIndex;
fast=slow=bIndex=head;
mIndex=NULL;
if(head==NULL) return false;
while(fast->next!=NULL&&fast->next->next !=NULL)
{
fast=fast->next->next;
slow= slow->next;
if(fast==slow)
{
mIndex=fast;
break;
}
}
if (mIndex) return true;
else return false;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *fast;
struct ListNode *slow;
struct ListNode *bIndex;
struct ListNode *mIndex;
fast=slow=bIndex=head;
mIndex=NULL;
if(head==NULL) return NULL;
while(fast->next!=NULL&&fast->next->next !=NULL)
{
fast=fast->next->next;
slow= slow->next;
if(fast==slow)
{
mIndex=fast;
while(bIndex!=mIndex)
{
bIndex=bIndex->next;
mIndex=mIndex->next;
}
return bIndex;
}
}
return NULL;
}