/**
 * 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) {
            slow = slow.next;
            fast = fast.next.next;

            //快指针遍历到头,证明没有成环
            if (fast == null) {
                return false;
            }

            //快指针追上慢指针,证明成环
            if (slow.val == fast.val) {
                return true;
            }
        }

        return false;
    }
}