当前位置: 首页 > 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.xdnf.cn/news/1032913.html

相关文章:

  • Spring Data JPA全面指南
  • Docker 在尝试连接 Docker Hub 时遇到网络问题(超时)
  • 在Docker上部署datalust/Seq日志服务系统
  • 【DSP笔记 · 第5章】数字滤波器的蓝图:从数学公式到硬件实现的艺术
  • React--》使用vite构建器打造高效的React组件库
  • Docker 基础使用
  • TryHackMe (THM) - SOC基础知识
  • Android音视频流媒体基础总结
  • excel中添加进度条
  • 从大模型到 AI 应用,一共需要几步?
  • Git 工作流与版本管理策略
  • JVM(1)——运行时数据区
  • Hive SQL 执行计划详解:从查看方法到优化应用
  • 学习昇腾开发的第一天--环境配置
  • RabbitMQ的交换机和队列概念
  • 精益数据分析(104/126):免费移动应用的用户活跃率与付费转化优化策略
  • STM32F4通用定时器TIM9-TIM14讲解及PWM呼吸灯实例解读
  • 1 Studying《Arm A715 Software Optimization Guide》
  • 【Python-Day 26】解锁时间魔法:深入解析 time 与 datetime 模块
  • 双重特征c++
  • 共享项目中使用Wpf和Winform——c# CAD二次开发
  • 浏览器指纹-探究前端如何识别用户设备
  • 2.4.1 ASPICE的编码与单元测试
  • 新能源汽车电子架构革命:深度解析AUTOSAR标准与实践
  • 基于U-Net与可分离卷积的肺部分割技术详解
  • error:MISCONF Redis is configured to save RDB snapshots
  • Android 蓝牙默认名称设置分析总结
  • Laravel模板Blade 用法 x-layouts.guest 和x-guest-layout 什么区别
  • 《深度学习:基础与概念》第一章 学习笔记与思考
  • 数据结构 学习 链表 2025年6月14日08点01分