/**
* 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;
}
ListNode slow = head;
ListNode fast =head;
// 用快指针当做while循环的原因是快指针移动的比较快
while(fast !=null && fast.next !=null) {
// 移动快慢指针
slow = slow.next;
fast =fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}