【力扣 简单 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);
}
相关推荐
hrrrrb1 小时前
【Python】文件处理(二)
开发语言·python
先知后行。2 小时前
QT实现计算器
开发语言·qt
掘根2 小时前
【Qt】常用控件3——显示类控件
开发语言·数据库·qt
自信的小螺丝钉4 小时前
Leetcode 146. LRU 缓存 哈希表 + 双向链表
leetcode·缓存·散列表
机器学习之心5 小时前
多目标鲸鱼优化算法(NSWOA),含46种测试函数和9个评价指标,MATLAB实现
算法·matlab·多目标鲸鱼优化算法·46种测试函数·9个评价指标
西阳未落5 小时前
C++基础(21)——内存管理
开发语言·c++·面试
古译汉书5 小时前
嵌入式铁头山羊STM32-各章节详细笔记-查阅传送门
数据结构·笔记·stm32·单片机·嵌入式硬件·个人开发
我的xiaodoujiao6 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
max5006006 小时前
基于Meta Llama的二语习得学习者行为预测计算模型
人工智能·算法·机器学习·分类·数据挖掘·llama
callJJ6 小时前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(2)
java·开发语言·后端·spring·ioc·di