Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (true) {
if (fast == null || fast.next == null) return null;
slow = slow.next;
fast = fast.next.next;
if (fast == slow) break;
}
//if(head==null||head.next==null||head.next.next==null) return null ;
//ListNode fast = head;
//ListNode slow = head;
//while(fast.next!=null&&fast.next.next!=null){
//fast=fast.next.next;
//slow=slow.next;
//if (fast==slow) break;}
slow = head;
while(slow!=head){
slow=slow.next;
fast=fast.next; }
return slow;
}
}