使用一个Set/Map 存放已经遍历过的节点,如果当前节点已经存在于Set/Map中,说明该节点之前已经被遍历过,也即存在环
import java.util.*; /** * class ListNode { * int val; * ListNode next; * } */ public class Solution { public boolean checkHasCycle(ListNode head) { if(head==null || head.next==null){ return false; } Set<ListNode> nodeSet=new HashSet(); while(head!=null){ if(nodeSet.contains(head)){ return true; } nodeSet.add(head); head=head.next; } return false; } }