双指针
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head)return 0;
if(!head->next)return 0;
auto fast=head->next;
while(head&&fast){
if(head==fast)return 1;
fast=fast->next;
if(fast)fast=fast->next;
else return 0;
head=head->next;
}
return 0;
}
};
哈希表
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head)return 0;
if(!head->next)return 0;
unordered_set<ListNode*>hashset;
while(head){
if(hashset.count(head))return 1;
else hashset.insert(head);
head=head->next;
}
return 0;
}
};