和书上不太一样,这里用的弗洛伊德龟兔算法 Fast指针 比 slow 每次多走一步,相遇之后,fast从头开始一次走一步,slow从当前开始每次走一步,两者再相遇点就是入口。
ListNode *EntryNodeOfLoop(ListNode *pHeadList) { if (pHeadList == NULL || pHeadList -> m_pNext == NULL) return NULL; ListNode *slow = pHeadList -> m_pNext , *fast = slow -> m_pNext; while (fast != NULL && slow != NULL) { if (fast == slow) break; // 第一次相遇 if (fast -> m_pNext == NULL) return NULL; // 没有环 else { fast = fast -> m_pNext -> m_pNext; // 前进 slow = slow -> m_pNext; } } if (fast != slow || fast == NULL) return NULL; // 没有环 fast = pHeadList; // fast从头走 while (fast != slow) { // 再一次相遇,相遇点就是入口 fast = fast -> m_pNext; slow = slow -> m_pNext; } return fast; }