题解 | #链表中环的入口结点#
链表中环的入口结点
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) {
// 空的情况
if (pHead == nullptr) return nullptr;
// 双指针法 快慢指针
ListNode* pSlow = pHead;
ListNode* pFast = pHead;
while(1){
// 移动不同的长度
pSlow = pSlow->next;
pFast = pFast->next->next;
if(pFast == nullptr || pSlow == nullptr){
break;
}
// 有环的话快指针会追上慢指针
if (pSlow == pFast) {
// 追上了 开始找环的入口
pSlow = pHead;
while (pSlow != pFast) {
pSlow = pSlow->next;
pFast = pFast->next;
}
return pSlow;
}
}
return nullptr;
}
};


