/**
 * 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;

        if(head.next == head) return true;

        ListNode fast = head.next;
        ListNode slow = head;
        boolean flag = false;
        while(fast!=slow){
            // 如果有空指针异常,则说明没有环
            try{
                fast = fast.next.next;
                slow = slow.next;
            }catch(Exception e){
                break;
            }
            if(fast == slow){
                flag = true;
                break;
            }

        }
        return flag;
    }
}