判断给定的链表中是否有环。如果有环则返回true,否则返回false。
数据范围:链表长度 0≤𝑛≤10000,链表中任意节点的值满足 ∣𝑣𝑎𝑙∣<=100000
要求:空间复杂度 𝑂(1),时间复杂度 𝑂(𝑛)
public class Solution {
public boolean Cycle(ListNode head) {
if (head==null)
return false;
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow)
return true;
}
return false;
}
}