思路:利用hash表的contains方法解决,将链表的结点依次放入hash表,并检查放入的节点是否存在过,若存在则有环;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode pos = head;
//利用hash表来记录链表的结点
Set<ListNode> hashset = new HashSet<>();
while (pos != null) {
//若节点再hash表中已经存在,说明有环
if (hashset.contains(pos)) {
return true;
} else {
hashset.add(pos);
}
pos = pos.next;
}
return false;
}
}