AcWing 34. 链表中环的入口结点
原题链接
中等
C++ 代码
// 快慢指针
/**
* 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) return nullptr;
auto first = head, second = head;
first = first->next, second = second->next->next; // 方便进入循环
while(first != second)
{
first = first->next; // 慢指针一次走一步
second = second->next->next; // 快指针一次走两步
if(!first || !second) return nullptr; // 若没有环,则直接返回 nullptr
}
// 此时就是第一次的相遇点
second = head;
while(first != second)
{
first = first->next;
second = second->next;
}
// 此时就是环入口
return second;
}
};