题目链接:https://www.acwing.com/problem/content/description/86/
快慢指针,快指针一次走两步,慢指针一次走一步,如果快指针无法继续前进,没有环;
否则,当快指针与慢指针第一次相遇以后,令快指针等于头结点,快慢指针各自每次走一步,再次相遇的点即为环的入口节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *entryNodeOfLoop(ListNode *head) {
if(!head || !head -> next) return nullptr;
ListNode* fast = head;
ListNode* low = head;
while(fast && low)
{
fast = fast -> next;
low = low -> next;
if(fast) fast = fast -> next;
else return nullptr;
if(fast == low)
{
fast = head;
while(fast != low)
{
fast = fast -> next;
low = low -> next;
}
return fast;
}
}
return nullptr;
}
};
原文:https://www.cnblogs.com/Trevo/p/12852885.html