检测一个linked list里是否有环,思想就是使用两个移动速度不同的指针,fast = fast.next.next; slow = slow.next;在退出循环的时候,如果fast == null或者fast.next == null,那么说明没有环,如果slow == fast,说fast指针赶上了slow,说明有环,复杂度的分析和代码如下:
/**
* 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) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
break;
}
if(fast == null || fast.next == null)
return false;
return true;
}
}
知识点:
1. 在linked list中使用两个指针,使用两个速度不同的指针,是一个重要的思想,值得记录
2. 注意这里在初始化fast指针的时候,使用了head.next,所以首先也要检测一下head.next是否为null
3. 这道题目非常经典