两种方法一个空间O(n),另一个O(1),时间都是O(n)。
one
class Solution {
public:bool hasCycle(ListNode *head) {unordered_set<ListNode*>set;while(head){if(set.count(head))return true;set.insert(head);head=head->next;}return false;}
};
two
class Solution {
public:bool hasCycle(ListNode *head) {if(!head||!head->next) return false;ListNode*slow=head,*fast=head->next;while(slow!=fast){if(!fast||!fast->next) return false;slow=slow->next;fast=fast->next->next;}return true;}
};
END