单向链表利用快慢指针

/**
 * 单链表的中点
 */
const middleNode = (node = linkList) => {
    let slow = node, fast = node;
    while(fast && fast.next){
        slow = slow.next
        fast = fast.next.next
    }
    return slow.value
}

/**
 * 判断链表是否包含环
 */
const hasCycle =  (node = linkList) => {
    let slow = node, fast = node;
    while(fast && fast.next){
        slow = slow.next
        fast = fast.next.next
        if(fast === slow){
            return true
        }
    }
    return false
}

  

posted @ 2023-01-30 20:38  671_MrSix  阅读(6)  评论(0编辑  收藏  举报