题解 | #链表中环的入口结点#
链表中环的入口结点
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||pHead->next==nullptr||pHead->next->next==nullptr) return NULL; ListNode* fast=pHead; ListNode*slow=pHead; do{ fast=fast->next; if(fast){ fast=fast->next; } else{ break; } slow=slow->next; }while(fast&&slow&&fast!=slow); if(fast==nullptr||slow==nullptr) return NULL; slow=pHead; while(fast!=slow){ fast=fast->next; slow=slow->next; } if(fast==slow) return fast; else return NULL; } //判断链表是否有环,快慢指针最后走到环入口点说明有环,那么此时快慢指针的位置就是环入口点 };