【力扣 简单 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);
}
相关推荐
消失的旧时光-194310 分钟前
Kotlin 协程最佳实践:用 CoroutineScope + SupervisorJob 替代 Timer,实现优雅周期任务调度
android·开发语言·kotlin
错把套路当深情17 分钟前
Kotlin保留小数位的三种方法
开发语言·python·kotlin
B站_计算机毕业设计之家28 分钟前
python电商商品评论数据分析可视化系统 爬虫 数据采集 Flask框架 NLP情感分析 LDA主题分析 Bayes评论分类(源码) ✅
大数据·hadoop·爬虫·python·算法·数据分析·1024程序员节
小白菜又菜1 小时前
Leetcode 1518. Water Bottles
算法·leetcode·职场和发展
长存祈月心1 小时前
Rust Option 与 Result深度解析
算法
赵谨言1 小时前
基于Python Web的大数据系统监控平台的设计与实现
大数据·开发语言·经验分享·python
cellurw1 小时前
Day72 传感器分类、关键参数、工作原理与Linux驱动开发(GPIO/I²C/Platform/Misc框架)
linux·c语言·驱动开发
专注前端30年2 小时前
Vue2 中 v-if 与 v-show 深度对比及实战指南
开发语言·前端·vue
杭州杭州杭州2 小时前
机器学习(3)---线性算法,决策树,神经网络,支持向量机
算法·决策树·机器学习
星竹晨L2 小时前
C++继承机制:面向对象编程的基石
开发语言·c++