/*
方法一:哈希表,将节点放入set中,如果set中已经有了这个节点,说明有环,返回即可
*/
// let list = new Set()
// while(head){
// if(list.has(head))
// return head
// list.add(head)
// head = head.next
// }
// return null
/*
方法二:快慢指针 a+b+n(b+c) = 2(a+b) => a= (n-1)(b+c)+c
在快慢指针相遇之后,定义指针ptr指向head,ptr和slow一起向后移,直到相遇,此时指针指向的就是环的入口
*/
let fast = head
let slow = head
while(fast!=null && fast.next!=null){
fast = fast.next.next
slow = slow.next
if(fast==slow){
let ptr = head
while(ptr!=slow){
ptr = ptr.next
slow = slow.next
}
return slow
}
}
return null
};
leetcode142 环形链表||
最新推荐文章于 2024-06-17 14:51:36 发布