1、想着用unordered_map来做,key是结点的数值val,value是设置的自己加的index,但是val是可能重复的,而index一直都在变,不可能判断出已经访问过的结点,结果就是找不到魂头!
2、官方用unordered_set来做,之前不知道这个东西,针不戳!不像map需要键值对,set只有一个参数。
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> visited;
for(; head != NULL; head = head->next){
if(visited.count(head) > 0){
return true;
}
visited.insert(head);
}
return false;
}
};