Linked List Cycle II
http://lintcode.com/en/problem/linked-list-cycle-ii/
math explanation: http://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next==null) {
return null;
}
ListNode fast, slow;
fast = head.next;
slow = head;
while (fast != slow) {
if(fast==null || fast.next==null)
return null;
fast = fast.next.next;
slow = slow.next;
}
while (head != slow.next) {
head = head.next;
slow = slow.next;
}
return head;
}
}