题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
快慢指针,求解链表环的模板解法。
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
if (!pHead || !pHead->next) return nullptr;
ListNode* fast = pHead->next->next, *slow = pHead->next;
while (fast && fast != slow) {
if (!fast->next) return nullptr;
fast = fast->next->next;
slow = slow->next;
}
if (!fast) return nullptr;
ListNode* res = pHead;
while (res != slow) {
res = res->next;
slow = slow->next;
}
return res;
}
};
查看24道真题和解析