【leetcode hot 100 142】环形链表Ⅱ
解法一:(哈希集合->同141)在循环过程中使用HashSet存放当前ListNode,若以前已经存放过,说明已经遍历过了->有环。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
ListNode temp = head;
while(temp!=null){
if(set.contains(temp)){
return temp;
}
set.add(temp);
temp = temp.next;
}
return null;
}
}