题解 | #链表中环的入口结点#
链表中环的入口结点
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) {
//fast low
//if have a cycle,fast==slow
ListNode* slow=hasCycle(pHead);
if(slow==nullptr)
return nullptr;//no cycle
//be sure there is cycle
ListNode* fast=pHead;
while(fast!=slow){
fast=fast->next;
slow=slow->next;
}//why
return slow;
}
ListNode* hasCycle(ListNode* head){
if(head==nullptr) return nullptr;
ListNode* fast=head;
ListNode* slow=head;
while(fast!=nullptr&&fast->next!=nullptr){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return slow;
}
return nullptr;
}
};
why:
公式推导
