当前位置: 首页 > 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);
}

相关文章:

  • 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无人机配置流程(五)
  • 网站建设优化网站排名/交换友链
  • 设计网站项目描述/友情链接的定义
  • 一站式网站建设平台/百度关键词点击价格查询
  • 潮汕美食网站怎么做/seo还有用吗
  • 哪个网站可以做效果图/百度推广一天烧多少钱
  • 中国十大小说网站排名/bt磁力搜索引擎