public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = head;
while (fast != null && slow != fast) {
slow = slow.next;
fast = fast.next;
if (fast != null) {
fast = fast.next;
}
}
if (slow != fast) {
return null;
}
int countCycle = 1;
ListNode p1 = slow.next;
while (p1 != slow) {
countCycle++;
p1 = p1.next;
}
ListNode p2 = head;
for (int i = 0; i < countCycle; i++) {
p2 = p2.next;
}
while (p2 != head) {
head = head.next;
p2 = p2.next;
}
return head;
}
}