142. 环形链表 II

leetCode链表
/**
 * 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
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
更新时间: 2022-03-25 17:04