public ListNode detectCycle(ListNode head) {HashSet<ListNode> set = new HashSet<ListNode>();while (head != null) {// 检查是否有重复添加if (!set.add(head)) {return head;}head = head.next;}return null;}
public class Solution {public ListNode detectCycle(ListNode head) {ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;if (slow == fast) {// 当快慢在点p处相遇时,它们运行的长度是“a + 2b + c”和“a + b”。// 因为快比慢快2倍。所以a+2b+c == 2(a+b),然后我们得到'a==c'。ListNode slow2 = head;while (slow != slow2) {slow = slow.next;slow2 = slow2.next;}return slow;}}return null;}}
https://leetcode.com/problems/linked-list-cycle-ii/discuss/44774/Java-O(1)-space-solution-with-detailed-explanation.-space-solution-with-detailed-explanation.)
