哈希
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head||!head->next)return false;
unordered_set<ListNode*>unset;
ListNode* cur=head;
while(cur){
if(unset.count(cur))return true;
else unset.insert(cur);
cur=cur->next;
}
return false;
}
};
双指针
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head||!head->next)return false;
ListNode *fast=head->next,*slow=head;
while(fast!=slow){
if(!fast||!fast->next)return false;
fast=fast->next->next;
slow=slow->next;
}
return true;
}
};