Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null){
return null;
}
ListNode fast=head.next.next;
ListNode slow=head.next;
while(fast!=slow){
if(fast==null||fast.next==null){
return null;
}
fast=fast.next.next;
slow=slow.next;
}
slow=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;