衔接上一篇------leetcode142环形链表

题目就不赘述了,直接思路和代码

在这里插入图片描述在这里插入图片描述

代码如下

/**
 * 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||!head.next){
        return null
    }
    let slow=head,fast=head
    while(fast&&fast.next){
        slow=slow.next
        fast=fast.next.next
        if(slow===fast){
            fast=head
            while(slow!==fast){
                slow=slow.next
                fast=fast.next
            }
            return fast
        }
    }
    return null
};

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wennianzhu/article/details/107127121