用哈希表来存储已经访问过的节点,当我们每次到到这个节点时,如果在哈希表中,就已经时访问过的,就能构成一个环。
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> hasCycleSet=new HashSet<ListNode>();
while(head!=null){
if(!hasCycleSet.add(head)){
return true;
}
head=head.next;
}
return false;
}
}