https://leetcode.com/problems/linked-list-cycle-ii/#/description
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. Follow up: Can you solve it without using extra space?
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
do {
if (fast == null || fast.next == null) {
return null;
}
fast = fast.next.next;
slow = slow.next;
} while (fast != slow);
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}