思路:利用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;
}
};
本文介绍了一种使用set数据结构来检测链表中是否存在回路的方法。通过遍历链表并将节点指针存入set中,若遇到已存在的节点则表明存在回路。

303

被折叠的 条评论
为什么被折叠?



