fastrunner and slowrunner trick
1 public class Solution { 2 public ListNode detectCycle(ListNode head) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 ListNode fastrunner = head; 6 ListNode slowrunner = head; 7 while(fastrunner != null && fastrunner.next != null) 8 { 9 fastrunner = fastrunner.next.next; 10 slowrunner = slowrunner.next; 11 if(slowrunner == fastrunner) 12 break; 13 } 14 if(fastrunner == null || fastrunner.next == null) 15 return null; 16 slowrunner = head; 17 while(slowrunner != fastrunner) 18 { 19 slowrunner = slowrunner.next; 20 fastrunner = fastrunner.next; 21 } 22 return slowrunner; 23 } 24 }