/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> seen;
while(head!=nullptr)
{
//使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0
if(seen.count(head))
{
return true;
}
seen.insert(head);
head=head->next;
}
return false;
}
};
06-20
354
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-02
163
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)