题解 | #链表中环的入口结点#
链表中环的入口结点
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->next;
if (pSlow == nullptr) return nullptr;
ListNode* pFast = pHead->next->next;
if (pFast == nullptr) return nullptr;
while (pFast != pSlow) {
if (pFast->next == nullptr || pFast->next->next == nullptr) {
return nullptr;
}
pFast = pFast->next->next;
pSlow = pSlow->next;
}
pSlow = pHead;
while (pSlow != pFast) {
pSlow = pSlow->next;
pFast = pFast->next;
}
return pFast;
}
};
2023 剑指-链表 文章被收录于专栏
2023 剑指-链表

查看9道真题和解析