目录
题目

解法一:哈希
cpp
struct node
{
struct ListNode* val;
struct node* next;
};
struct hashSet
{
struct node** bucket;
int size;
};
struct hashSet* hashSetInit(int size)
{
struct hashSet* hashSet = malloc(sizeof(*hashSet));
hashSet->bucket = calloc(size, sizeof(*hashSet->bucket));
hashSet->size = size;
return hashSet;
}
long long hash(struct hashSet* hashSet, struct ListNode* val)
{
return ((long long)val >> 7) % hashSet->size;
}
void hashSetInsert(struct hashSet* hashSet, struct ListNode* val)
{
long long index = hash(hashSet, val);
struct node* newNode = malloc(sizeof(*newNode));
newNode->val = val;
newNode->next = hashSet->bucket[index];
hashSet->bucket[index] = newNode;
}
bool hashSetFind(struct hashSet* hashSet, struct ListNode* val)
{
long long index = hash(hashSet, val);
struct node* curNode = hashSet->bucket[index];
while (curNode)
{
if (curNode->val == val)
return true;
curNode = curNode->next;
}
return false;
}
void hashSetFree(struct hashSet* hashSet)
{
for (int i = 0; i < hashSet->size; i++)
{
struct node* freeNode = hashSet->bucket[i];
while (freeNode)
{
struct node* nextNode = freeNode->next;
free(freeNode);
freeNode = nextNode;
}
}
free(hashSet->bucket);
free(hashSet);
}
bool isCycle(struct ListNode* head)
{
struct hashSet* hashSet = hashSetInit(512);
struct ListNode* curNode = head;
bool is = false;
while (curNode)
{
if (hashSetFind(hashSet, curNode))
{
is = true;
break;
}
hashSetInsert(hashSet, curNode);
curNode = curNode->next;
}
hashSetFree(hashSet);
return is;
}
bool hasCycle(struct ListNode* head)
{
return isCycle(head);
}
解法二:快慢指针
cpp
bool isCycle(struct ListNode* head)
{
struct ListNode* fast = head;
struct ListNode* slow = head;
while (fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
return true;
}
return false;
}
bool hasCycle(struct ListNode* head)
{
return isCycle(head);
}