1 package leetcode; 2 3 public class DetectCycle { 4 public ListNode detectCycle(ListNode head) { 5 ListNode s=head; 6 ListNode f=head; 7 while(f!=null&&f.next!=null){ 8 s=s.next; 9 f=f.next.next; 10 if(s==f){ 11 break; 12 } 13 } 14 if(f==null||f.next==null) 15 return null; 16 s=head; 17 while(s!=f){ 18 s=s.next; 19 f=f.next; 20 } 21 return s; 22 } 23 }