- 142.环形链表II
-
class Solution { public ListNode detectCycle(ListNode head) { ListNode fast, slow; fast = slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) break; } // 注意:必须在这个位置判空 if (fast == null || fast.next == null) { // fast 遇到空指针说明没有环 return null; } // 重新指向头结点 slow = head; // 快慢指针同步前进,相交点就是环起点 while (slow != fast) { fast = fast.next; slow = slow.next; } return slow; } }