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

目录

题目

解法一:哈希

解法二:快慢指针


题目

解法一:哈希

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);
}
相关推荐
智者知已应修善业几秒前
【51单片机1,左边4个LED灯先闪烁2次后,右边4个LED灯再闪烁2次:2,接着所用灯一起闪烁3次,接着重复步骤1,如此循环。】2023-5-19
c++·经验分享·笔记·算法·51单片机
米啦啦.几秒前
红黑树,,
数据结构·红黑树
xyq20241 分钟前
Java 变量命名规则
开发语言
天启HTTP1 分钟前
HTTP代理和隧道代理的底层区别与适用场景分析
开发语言·网络协议·tcp/ip·php
小白学大数据3 分钟前
告别复杂 XPath:DeepSeek+Python 爬虫快速实践
开发语言·爬虫·python·selenium
xiaoye-duck7 分钟前
《算法题讲解指南:优选算法-队列+宽搜》--70.N叉树的层序遍历,71.二叉树的锯齿形层序遍历,72.二叉树的最大宽度,73.在每个树行中找最大值
数据结构·c++·算法·队列
汀、人工智能9 分钟前
[特殊字符] 第98课:数据流中位数
数据结构·算法·数据库架构··数据流·数据流中位数
fengci.10 分钟前
LilCTF2025web(前半部分)
开发语言·网络·学习·php
REDcker11 分钟前
C++ 包管理工具概览
开发语言·c++
Eloudy12 分钟前
不同特征值的特征向量互相正交的矩阵
人工智能·算法·机器学习