【力扣 简单 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);
}
相关推荐
p***43482 分钟前
Rust网络编程模型
开发语言·网络·rust
ᐇ95914 分钟前
Java集合框架深度实战:构建智能教育管理与娱乐系统
java·开发语言·娱乐
梁正雄43 分钟前
1、python基础语法
开发语言·python
.YM.Z1 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong3451 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
强化学习与机器人控制仿真1 小时前
RSL-RL:开源人形机器人强化学习控制研究库
开发语言·人工智能·stm32·神经网络·机器人·强化学习·模仿学习
百***48071 小时前
【Golang】slice切片
开发语言·算法·golang
q***92511 小时前
Windows上安装Go并配置环境变量(图文步骤)
开发语言·windows·golang
墨染点香1 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展
做怪小疯子1 小时前
LeetCode 热题 100——链表——反转链表
算法·leetcode·链表