Appearance
142. 环形链表 II
js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
if(head == null) return null
let slow = head
let fast = head
let p = head
while (fast !== null && fast.next !== null) {
slow = slow.next
fast = fast.next.next
// 如果有环形链表
if(slow === fast) {
// slow和p一起走,交叉的地方就是环形的头部
while (slow !== p) {
slow = slow.next
p = p.next
}
return p
}
}
return null
};