题解
public class Solution {
public boolean hasCycle(ListNode head) {
// 快慢指针初始化指向 head
ListNode slow = head, fast = head;
// 快指针走到末尾时停止
while (fast != null && fast.next != null) {
// 慢指针走一步,快指针走两步
slow = slow.next;
fast = fast.next.next;
// 快慢指针相遇,说明含有环
if (slow == fast) {
return true;
}
}
// 不包含环
return false;
}
}
// 详细解析参见:
// https://labuladong.online/algo/essential-technique/linked-list-skills-summary/
思路
[!hint]
- 看到环问题,首先想到快慢指针
- 一个步长大于另一个,链表成环的情况下,两个指针必定相遇
- 环检测的复杂度 = 遍历链表的时间复杂度
- 假如遍历完成,说明没有成环
- 记住遍历的条件,并在过程中校验
