/**
* 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 == nullptr){
return nullptr;
}
ListNode* q = head;ListNode* p = head;
//找到快慢指针第一相遇的位置
while(q && q->next){
q = q->next->next;
p = p->next;
if(q==p){
//将慢指针置于头结点位置,两者步速相同,再次相遇时,走了起点到环节点的距离,两者再次相遇点是环的起点
p = head;
while(q != p ){
q = q->next;
p = p->next;
}
return q;
}
}
return nullptr;
}
};