①***用哈希表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> v; //用哈希表存储
ListNode* p=head;
while(p){
if(v.count(p)) return p; //在哈希表中查找
v.insert(p);
p=p->next;
}
return NULL;
}
};
②*****快慢指针
核心思想:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast=head,*slow=head;
if( !fast || !fast->next) return NULL;
while(fast){
slow=slow->next;
if(!fast->next) return NULL;
fast=fast->next->next;
if(fast==slow){ //找到相遇点
ListNode* p=head; //slow从相遇点继续,p从头结点开始出发,p到达入环点时,slow也会转到入环点(可证明)
while(p!=slow){
p=p->next;
slow=slow->next;
}
return p;
}
}
return NULL;
}
};