思路:利用set中不会包含重复元素的特点,遍历List,每次将遍历的节点存入set,一旦发现该节点已经在set中,则表示有回路。
#include<set>
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *tmp = head,*p;
set<ListNode*> num;
while(tmp)
{
p = tmp;
if(num.find(p)!=num.end())return true;
else
{
num.insert(p);
}
tmp = tmp->next;
}
return false;
}
};