题解 | #链表中环的入口结点#
链表中环的入口结点
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* fast = pHead; ListNode* slow = pHead; while(fast != nullptr && fast->next != nullptr) { //一个走一步一个走两步,如果有环一定相遇 fast = fast->next->next; slow = slow->next; //相遇了跳出 if(fast == slow) break; } //判断是不是break跳出的循环,是则有环 if(fast == nullptr || fast->next == nullptr) return nullptr; //head到入口的距离等于相遇点到入口的距离加上(n)个环的长度r slow = pHead; while(slow != fast) { fast = fast->next; slow = slow->next; } return fast; } };