第一次相遇说明,这个链表中有环
第二次相遇说明,这个环的入口点
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null) return null; ListNode slow = head; ListNode fast = head; while(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; if(slow == fast){ ListNode k1 = head; while(k1 != slow){ k1 = k1.next; slow = slow.next; } return k1; } } return null; } }