欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 【力扣 简单 C】141. 环形链表

【力扣 简单 C】141. 环形链表

2025/12/17 1:09:57 来源:https://blog.csdn.net/2503_92320911/article/details/148654665  浏览:    关键词:【力扣 简单 C】141. 环形链表

目录

题目

解法一:记录遍历过的结点(哈希集合)

解法二:快慢指针


题目

解法一:记录遍历过的结点(哈希集合)

typedef struct hashSetListNode
{void* val;struct hashSetListNode* next;
} hashSetListNodeType;typedef struct hashSet
{hashSetListNodeType** bucket;uint32_t size;
} hashSetType;hashSetType* hashSetInit(uint32_t size)
{hashSetType* hashSet = malloc(sizeof(*hashSet));hashSet->bucket = calloc(size, sizeof(*hashSet->bucket));hashSet->size = size;return hashSet;
}// FNV-1a
uint32_t hash(const uint8_t* data, uint32_t len)
{uint32_t hash = 0x811c9dc5;for (int i = 0; i < len; i++){hash ^= data[i];hash *= 0x01000193;}return hash;
}void hashSetInsert(hashSetType* hashSet, void* val)
{uint32_t index = hash((uint8_t*)&val, sizeof(val)) % hashSet->size;hashSetListNodeType* newNode = malloc(sizeof(*newNode));newNode->val = val;newNode->next = hashSet->bucket[index];hashSet->bucket[index] = newNode;
}bool hashSetFind(hashSetType* hashSet, void* val)
{uint32_t index = hash((uint8_t*)&val, sizeof(val)) % hashSet->size;hashSetListNodeType* curNode = hashSet->bucket[index];while (curNode){if (curNode->val == val)return true;curNode = curNode->next;}return false;
}void hashSetFree(hashSetType* hashSet)
{for (int i = 0; i < hashSet->size; i++){hashSetListNodeType* freeNode = hashSet->bucket[i];while (freeNode){hashSetListNodeType* nextNode = freeNode->next;free(freeNode);freeNode = nextNode;}}free(hashSet->bucket);free(hashSet);
}bool check(struct ListNode* head)
{hashSetType* 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 check(head);
}

解法二:快慢指针

bool check(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 check(head);
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com