题目链接:https://leetcode-cn.com/problems/linked-list-cycle/
题目如下:
/**
* 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) {
//tip: unordered_set
//a.find("1234") set中不可为空,若找不到,则返回a.end();
//a.count("1234") set中可以为空,其中元素不可重复,故返回值为0或1
unordered_set<ListNode*> hash_set;
while(head){
if(hash_set.count(head)) return true;
else hash_set.insert(head);
head=head->next;
}
return false;
}
};