判断链表是否有环
//给定一个链表判断是否有环
//思路:快慢指针和HashSet都可以做,前者可以有O(1)较小的空间复杂度,后者至少是O(n)
//给出最优的做法
public class Solution{
public boolean hasCycle(ListNode head){
if(head==null||head.next==null) return false;
ListNode slow=head;
ListNode fast=head.next;
while(slow!=fast){
if(fast==null||fast.next==null) retrun false;
slow=slow.next;
fast=fast.next.next;
}
return true;
}
}

浙公网安备 33010602011771号