class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1 != index2)
{
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
// 不能将index1在此处返回,因为index1在if代码块执行结束之后,会被自动释放
}
return NULL;
}
};
标签:slow,ListNode,环形,fast,next,链表,index1
From: https://www.cnblogs.com/dh2021/p/16831157.html