1. public ListNode detectCycle(ListNode head) {
    2. HashSet<ListNode> set = new HashSet<ListNode>();
    3. while (head != null) {
    4. // 检查是否有重复添加
    5. if (!set.add(head)) {
    6. return head;
    7. }
    8. head = head.next;
    9. }
    10. return null;
    11. }
    1. public class Solution {
    2. public ListNode detectCycle(ListNode head) {
    3. ListNode slow = head;
    4. ListNode fast = head;
    5. while (fast != null && fast.next != null) {
    6. slow = slow.next;
    7. fast = fast.next.next;
    8. if (slow == fast) {
    9. // 当快慢在点p处相遇时,它们运行的长度是“a + 2b + c”和“a + b”。
    10. // 因为快比慢快2倍。所以a+2b+c == 2(a+b),然后我们得到'a==c'。
    11. ListNode slow2 = head;
    12. while (slow != slow2) {
    13. slow = slow.next;
    14. slow2 = slow2.next;
    15. }
    16. return slow;
    17. }
    18. }
    19. return null;
    20. }
    21. }

    https://leetcode.com/problems/linked-list-cycle-ii/discuss/44774/Java-O(1)-space-solution-with-detailed-explanation.-space-solution-with-detailed-explanation.)