
用快慢指针的方法
根据推出的表达式:slow和fast相遇的时候,让slow和位于头节点的p同时
向前走,刚好在入环的节点处相遇!注意:b和c交界的点不一定是从例如-4这个节点处,
可能是0节点处。因为相遇的点只能是在2、0、-4这几个点,c的长度并不一定是一个next就可以
到达入环口的长度!
重点是理解a b c的关系!

 public ListNode detectCycle1(ListNode head) {
        Set<ListNode> visited = new HashSet<>();
        while (head != null) {
            if (visited.contains(head)) return head;
            visited.add(head);
            head = head.next;
        }
        return null;
    }
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                ListNode p = head;
                while (p != slow) {
                    p = p.next;
                    slow = slow.next;
                }
                return p;
            }
        }
        return null;
    }
                



![[lesson22]对象的销毁](https://img-blog.csdnimg.cn/direct/7d1b075e67ec44e68fb2404176dd9d2c.png#pic_center)
















