给定一个链表,判断链表中是否有环。
思路:
1.快慢指针,fast=head.next slow=head
2.如果有环,快指针必将追上慢指针 如果没环,fast==null || slow == null return false
var hasCycle = function(head) {
if(head==null || head.next==null) return false
let fast = head.next
let slow = head
while(slow!=fast){
if(fast==null || fast.next==null){
return false
}
slow = slow.next
fast = fast.next.next
}
return true
};