public class Solution { public ListNode detectCycle(ListNode head) { //如果没有长度或者长度是1自然不是环 if(head == null || head.next == null){ return null; } ListNode slow = head; ListNode fast = head.next; while(slow != fast){ if(fast == null || fast.next == null){ return null; } slow = slow.next; fast = fast.next.next; } //slow 继续走,fast从head开始重新走,每次走一步直到两个相遇 fast = head; while (slow != fast){ slow = slow.next; fast = fast.next; } fast = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return fast; }}