// 解法:官方快慢指针 publicbooleanhasCycle_slow_gov(ListNode head) { if (head == null || head.next == null) returnfalse; ListNodeslow= head, fast = head.next; while (slow != fast) { if (fast == null || fast.next == null) returnfalse; slow = slow.next; fast = fast.next.next; } returntrue; }
// 解法:快慢指针 publicbooleanhasCycle_slow(ListNode head) { booleanflag=false; ListNodeslow= head, fast = head.next; while (fast != null && slow != null) { if (flag) slow = slow.next; fast = fast.next; flag = !flag; if (fast == slow) returntrue; } returnfalse; }
// 解法:空间换时间 publicbooleanhasCycle_area(ListNode head) { Set<ListNode> set = newHashSet<>(); while (head != null) { if (set.contains(head)) returntrue; set.add(head); head = head.next; } returnfalse; } }
4,扩展知识
Floyd 判圈算法,又称龟兔赛跑算法(Tortoise and Hare Algorithm),是一个可以在有限状态机、迭代函数或者链表中判断是否存在环,以及找出该环的起点和长度的算法。以下是对该算法的详细介绍: 算法原理 该算法使用两个指针,一个慢指针(龟)和一个快指针(兔)。慢指针每次移动一步,快指针每次移动两步。如果存在环,快指针最终会追上慢指针。