import java.util.*;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
// 原理: 快指针 a 一次走两步 满指针 b 一次走一步 类似于 a的速度是 2 b的速度是 1
//他们 相对速度是 1 可以想象为 b 没有动 a 一致走一步 加入 a能找到 b 说明有环 反之无环
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
// fast != null && fast.next != null 这个顺序不能反过来
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
// 退出循环 说明块指针找到了null 表示 没有环 如果没有退出循环 在里面找到了slow ==fast 表示有环纯在
return false;
}
}