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) {
        if(head == null || head.next ==  null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next !=null &&fast.next.next !=null){
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}

如果有环的话,那么代码中的while是不会结束的,那么slow每次移动一个单位,fast移动两个,终将会有一次会相遇,然后返回 true就行了,其他的情况就返回false