Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

876. 链表的中间结点 #29

Open
zpc7 opened this issue Aug 8, 2022 · 0 comments
Open

876. 链表的中间结点 #29

zpc7 opened this issue Aug 8, 2022 · 0 comments
Labels
简单 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 8, 2022

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;
};
@zpc7 zpc7 added JS 简单 LeetCode 难度定级 and removed JS labels Aug 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
简单 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant