Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null) return null;
ListNode slow=head;
ListNode fast=head;
int count=0;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
count++;
if(slow==fast) break;
}
if(slow==fast&&count!=0){
ListNode res=head;
while(res!=slow){
res=res.next;
slow=slow.next;
}
return res;
}else{
return null;
}
}
}