struct ListNode* EntryNodeOfLoop(struct ListNode* pHead ) {
if (pHead == NULL)
return NULL;
struct ListNode* fast = pHead;
struct ListNode* slow = pHead;
while(fast != NULL && fast->next != NULL){
slow = slow->next; //走一步
fast = fast->next->next; //走两步
if(slow == fast) break; //相遇→有环,退出while循环
}
if(fast == NULL || fast->next == NULL)
return NULL; //无环时快指针先到链尾
fast = pHead; //也可让慢指针回到链头重新开始
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}

京公网安备 11010502036488号