1. Use the "fast and slow pointer" to find the first meeting point;
2. One starts from the head node, and the other starts from the first meeting point;
3. When you meet again is the entry point.
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
#include <cstddef>
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
if(pHead==NULL || pHead->next==NULL) return NULL;
ListNode *slow=pHead, *fast=pHead;
while(fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(fast==slow) break;
}
if(fast==NULL || fast->next==NULL) return NULL;
ListNode *src=pHead;//指向头节点
ListNode *tmp=slow;//指向第一次相遇的节点
while(src!=tmp){
src=src->next;
tmp=tmp->next;
}
return src;
}
};
reference:
(285 messages) The entry node of the ring in the linked list---C++ implementation-CSDN Blog