题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode *pFast=pHead, *pSlow = pHead; while (pFast != nullptr) { if (pFast->next == nullptr) return nullptr; pSlow = pSlow->next; // 慢指针一次一步 pFast = pFast->next->next; // 快指针一次2步 if(pSlow == pFast) // 两者相遇 { pFast = pHead; // 快指针回到链表头 while (pFast != pSlow) { pFast = pFast->next; // 快慢指针都是一步一步走,直到再次相遇,即为环入口 pSlow = pSlow->next; } return pFast; } } return nullptr; } };