142. 环形链表 II
题解
与 141. 环形链表 不同的点在于本题要求返回环的入口,寻找环的入口是本题难点。
快慢指针
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
// 说明有环
if (fast == slow) {
ListNode tmp = head;
// 找到环的第一个
while (tmp != slow) {
tmp = tmp.next;
slow = slow.next;
}
return tmp;
}
}
return null;
}
}
哈希表
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return head;
} else {
set.add(head);
}
head = head.next;
}
return null;
}
}