import java.util.*;
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
       HashSet<ListNode> set = new HashSet<>();
       while(head != null){
        if(set.contains(head)){
            return true;
        }
        set.add(head);
        head = head.next;
       }
       return false;
    }
}

这个方法是使用hashset来存储已经遍历过的节点 如果set中已经有了这个节点 那么自然就是成环了

https://chatgpt.com/share/6923d572-8bec-800c-8e17-4412297c6ef2

这里问了一下gpt 介绍了一下hashset