Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

链表的中间结点

Sunny-117 opened this issue · comments

commented

快慢指针,快的一次走两个节点,慢的一次走一个节点.
当快指针走完后,慢指针指向的是中间节点

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function(head) {
    let fast = slow = head;

    while(fast && fast.next){
        fast = fast.next.next;
        slow = slow.next;
    }
    return slow;
};