/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//
两个指针slow和fast,都从链表头开始走,s每次走一步,f每次走两步,等两个指针重合时,就说明有环,否则没有。如果有环的话,那么让s指向链表头,f不动,两个指针每次都走一步,当它们重合时,所指向的节点就是环开始的节点。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL || head->next==NULL) return NULL;
ListNode* slow=head;
ListNode* fast=head;
while(fast->next!=NULL && fast->next->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(fast==slow){
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return slow;
}
}
return NULL;
}
};