2021/04/26
理解了 原理 之后手写一遍过。
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
boolean hasCircle = false;
while (slow != null && fast != null) {
slow = slow.next;
fast = fast.next;
if (fast == null) {
break;
}
fast = fast.next;
if (fast == slow) {
hasCircle = true;
break;
}
}
if (!hasCircle) return null;
ListNode p = head;
while (p != slow) {
p = p.next;
slow = slow.next;
}
return p;
}
}