https://leetcode-cn.com/problems/linked-list-cycle/
思路
快慢指针
循环条件注意避免空指针异常, 需要判断 fast != null && fast.next != null
/*
思路: 快慢指针
*/
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
// 快指针
ListNode fast = head;
// 慢指针
ListNode slow = head;
// 快慢指针同时移动, 循环条件直接判断 fast 即可, 并且是 fast != null && fast.next != null 避免空指针
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}