// 双指针 快+1=慢 true
class ListNode {
constructor(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
}
var hasCycle = function(head) {
let fast=head
let slow=head
while(fast&&slow&&fast.next){
if(fast.next===slow){
return true
}else{
fast=fast.next.next
slow=slow.next
}
}
return false
};
let arr = [1,2]
let head=buildLinkedList(arr)
head.next = head;
console.log(hasCycle(head));
function buildLinkedList(arr) {
let head = new ListNode(0);
let p = head;
for (let i = 0; i < arr.length; i++) {
p.next = new ListNode(arr[i]);
p = p.next;
}
return head.next;
}