Skip to content

876. 链表的中间结点 #29

Open
@zpc7

Description

@zpc7

876. 链表的中间结点

参考题解: https://leetcode.cn/problems/middle-of-the-linked-list/solution/lian-biao-de-zhong-jian-jie-dian-by-leetcode-solut/

通用解法

var middleNode = function (head) {
    // 统计链表的节点数
    let count = 1;
    let currentHead = head;
    while (currentHead.next) {
        count++;
        currentHead = currentHead.next;
    }
    const middleNodeIndex = Math.floor(count / 2) + 1;
    let secondHead = head;
    for (let i = 1; i <= count; i++) {
        if (i === middleNodeIndex) {
            return secondHead
        } else {
            secondHead = secondHead.next
        }
    }
};

快慢指针

var middleNode = function(head) {
    slow = fast = head;
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    简单LeetCode 难度定级

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions