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) {
        // 解题思路:从相同位置出发,一个步长为1,一个步长为2,如果有环最终会相遇
        if(head == null){
            return false;
        }

        ListNode n1 = head;
        ListNode n2 = head;

        while(n2 != null && n2.next != null){
            n1 = n1.next;
            n2 = n2.next.next;

            if(n1 == n2){
                return true;
            }
        }

        return false;
        
    }
}