(也是 leetcode 的142)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode s = head;
ListNode f = head;
while (true) {
if (f == null || f.next == null) {
return null;
}
s = s.next;
f = f.next.next;
if (s == f) {
break;
}
}
ListNode ptr = head;
while (ptr != s) {
ptr = ptr.next;
s = s.next;
}
return ptr;
}
}