【力扣 简单 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);
}
相关推荐
tanyongxi6617 分钟前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
qq_5139704418 分钟前
力扣 hot100 Day76
算法·leetcode·职场和发展
遗憾皆是温柔19 分钟前
24. 什么是不可变对象,好处是什么
java·开发语言·面试·学习方法
wearegogog12340 分钟前
C语言中的输入输出函数:构建程序交互的基石
c语言·开发语言·交互
Fine姐43 分钟前
The Network Link Layer: 无线传感器中Delay Tolerant Networks – DTNs 延迟容忍网络
开发语言·网络·php·硬件架构
Moshow郑锴1 小时前
机器学习相关算法:回溯算法 贪心算法 回归算法(线性回归) 算法超参数 多项式时间 朴素贝叶斯分类算法
算法·机器学习·回归
HAPPY酷1 小时前
给纯小白的Python操作 PDF 笔记
开发语言·python·pdf
liulilittle1 小时前
BFS寻路算法解析与实现
开发语言·c++·算法·宽度优先·寻路算法·寻路
剪一朵云爱着1 小时前
PAT 1065 A+B and C (64bit)
算法·pat考试
阿珊和她的猫1 小时前
autofit.js: 自动调整HTML元素大小的JavaScript库
开发语言·javascript·html