/**
* 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) {
ListNode fast;
ListNode slow;
fast = head;
slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) break;
}
// fast 遇到空指针说明没有环
if (fast == null || fast.next == null) {
return null;
}
slow = head;
while (slow != fast) {
fast = fast.next;
slow = slow.next;
}
// 再次相遇的节点为环的起点
return fast;
}
}