(链表,快慢指针扫描) O(n)
y总题解AcWing 34. 链表中环的入口结点 - AcWing
/**
* 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 0;//如果链表为空
auto i=head,j=head;//创建两个快慢指针
while(i&&j)
{
i=i->next;
j=j->next;
if(j)
{
j=j->next;
}
else return NULL;
if(i==j) //即相遇在c点;
{
i=head;
while(i!=j)
{
i=i->next;
j=j->next;
}
return i;
}
}
return NULL;
}
};