/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
*/
首先判断链表是否有环,使用快慢指针,在链表有环的情况下,继续判断环的开始结点。
ListNode *detectCycle(ListNode *head) {
if(head==NULL || head->next==NULL)
return NULL;
ListNode*slow=head;
ListNode*fast=head;
while(fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){ //有环
ListNode* x=head;
ListNode *y=slow;
while(x!=y){
x=x->next;
y=y->next;
} //这个地方可以用数学公式推一下,可以计算出一个指针从链表的头结点开始移动,另一个指针从快慢指针相交的地方开始移动,最终会相交于环的开始结点
return x;
}
}
return NULL;
}