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) {
        //采用快慢指针法来判断是否有环,一个指针走一步,一个指针走两步,
        // 如果走到了最后,说明无环,如果慢指针追上了快指针,说明有环
        ListNode firstNode = head;
        ListNode secondNode = head;
        while (firstNode != null && secondNode != null) {
            firstNode = firstNode.next == null ? null : firstNode.next.next;
            secondNode = secondNode.next;
             if (firstNode != null && firstNode == secondNode) {
                return true;
            }
        }
        return false;
    }
}