力扣https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode-solution/
方法一:哈希表
package com.company.linked;
import java.util.HashSet;
import java.util.Set;
public class Solution2 {
public ListNode detectCycle(ListNode head) {
Set seen = new HashSet();
while (head != null) {
if (!seen.add(head)) {
return head;
}
head = head.next;
}
return null;
}
}
方法二:快慢指针
package com.company.linked;
public class Solution2_1 {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head, fast = head;
while (fast != null) {
slow = slow.next;
if (fast.next != null) {
fast = fast.next.next;
} else {
return null;
}
//从相遇点开始计算
if (fast == slow) {
ListNode ptr = head;
//双指针速度相同,走到相遇的时候,ptr就走到入环的第一个节点
while (ptr != slow) {
ptr = ptr.next;
slow = slow.next;
}
return ptr;
}
}
return null;
}
}