题目
题目链接
题目要求
解题思路
显而易见的是,单纯的遍历循环是肯定不行的,既然是循环,关键就是要找到重复的地址,用值判断不行的,可能有重复的值。
方法一:哈希表
1,用哈希表储存节点指针的值,找到重复的则返回TRUE。
class Solution {
public:
bool HasCycle(ListNode *head)
{
unordered_set<ListNode*> hashtable; //哈希表
while (head != nullptr)
{
if (hashtable.count(head))
{
//如果当前节点已经有存储,则说明有重复
return true;
}
//插入节点
hashtable.insert(head);
head = head->next;
}
return false<