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) {
//头结点不存在,也就是没有环
if (head == null) {
return false;
}
//如果头结点的next域存着头结点的地址,那就是与自身为环
if (head.next == head) {
return true;
}
//创建两个指针(快慢指针),同时指向头结点
ListNode fast = head;
ListNode slow = head;
//fast走两步会先一步走到链表尾部,slow走一步
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
//如果fast不为空且fast.next也不为空,fast一定会跟slow相遇
if (fast == slow) {
return true;
}
}
/**
* while循环走完,fast一定没有跟slow相遇
*/
return false;
}
}