力扣 LeetCode 142. 环形链表II(Day2:链表)
解题思路:
使用set判断是否重复添加,如果set加入不进去证明之前到达过该节点,有环
public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
ListNode cur = head;
while (cur != null) {
boolean tag = set.add(cur);
if (tag == false) return cur;
cur = cur.next;
}
return null;
}
}