当前位置: 首页 > news >正文

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

目录

题目

解法一:哈希

解法二:快慢指针


题目

解法一:哈希

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);
}

解法二:快慢指针

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);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.dtcms.com/a/250334.html

相关文章:

  • LeetCode 第72题:编辑距离(巧妙的动态规划方法)
  • MCP前后端技术研究和应用实践
  • 中科院医学1区Top:解放军医学院利用多组学+网络药理学+转录组测序联合解析苗药七角生白胶囊抗白细胞减少症的分子机制
  • DataHub 架构设计与核心工作原理
  • Python----OpenCV(图像的绘制——绘制直线,绘制矩形,绘制圆形,绘制多边形)
  • win11修改DNS
  • python基础与数据类型
  • 【和春笋一起学C++】(十九)C++函数新特性——对象的引用作为函数参数
  • springAI 大模型应用开发
  • WooCommerce独立站商城的最大优势
  • PCB设计杂谈之一
  • C# 中的Async 和 Await 的用法详解
  • Python应用八股文
  • Java大模型开发入门 (10/15):连接外部世界(下) - 端到端构建完整的RAG问答系统
  • 高效同步Linux服务器文件技巧
  • 计算机网络-自顶向下—第二章应用层-重点复习笔记
  • vue3+ts实现全屏效果
  • 力扣面试150题--添加与搜索单词 - 数据结构设计
  • Redux 原理深度剖析
  • PX4无人机|MID360使用FAST_LIO,实现自主定位及定点——PX4无人机配置流程(五)
  • CTFshow-PWN-栈溢出(pwn56-pwn59)
  • 2025-06-14【视觉】批量筛选图集中包含某种物体对象的方法
  • 解决ModuleNotFoundError: No module named ‘open_clip‘
  • 多项目状态如何集中监控与汇总
  • 基于开源AI大模型与智能工具的优质内容引流策略研究——以AI智能名片及S2B2C商城小程序源码应用为例
  • 禾川伺服驱动器与EtherCAT主站转Profinet网关的双向数据交换
  • 纯 CSS 实现的的3种扫光效果
  • 基于STM32人脸识别系统
  • (LeetCode每日一题) 2566. 替换一个数字后的最大差值 ( 贪心 )
  • pytorch2.6安装