环形链表II
js
var detectCycle = function(head) {
let fast = head
let slow = head
while(fast && fast.next) {
fast = fast.next.next
slow = slow.next
if(fast === slow) break // 找到相遇节点
}
// 如果快指针(或其next)为null,则return null
if(fast === null || fast.next === null) return null
// 慢指针回到头节点
slow = head
while(slow !== fast) {
// 快慢指针同步前进,相交点就是环起点
slow = slow.next
fast = fast.next
}
return fast // 返回fast或者slow
}