欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

算法:环形链表

发布时间:2025/6/15 编程问答 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 算法:环形链表 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

 题目:判断链表是否有环

//环形链表//哈希表 func hasCycle(head *ListNode) bool {seen := map[*ListNode]struct{}{}for head != nil {if _, ok := seen[head]; ok {return true}//标记该节点已被访问seen[head] = struct{}{}head = head.Next}return false }//快慢指针 func hasCycle(head *ListNode) bool {if head == nil || head.Next == nil {return false}slow, fast := head, head.Nextfor fast != slow {if fast == nil || fast.Next == nil {return false}//慢指针一次移动2步slow = slow.Next//快指针一次移动2步fast = fast.Next.Next}return true }

链接:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/

总结

以上是生活随笔为你收集整理的算法:环形链表的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。