Skip to content
On this page

876. 链表的中间节点

原题链接:LeetCode 876. 链表的中间节点

题目描述

给你单链表的头结点 head ,请你找出并返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

示例 1:

**输入:**head = [1,2,3,4,5] 输出:[3,4,5] **解释:**链表只有一个中间结点,值为 3 。

示例 2:

**输入:**head = [1,2,3,4,5,6] 输出:[4,5,6] **解释:**该链表有两个中间结点,值分别为 3 和 4 ,返回第二个结点。

提示:

- 链表的结点数范围是 `[1, 100]`

- `1 <= Node.val <= 100`

难度: Easy


题解代码

javascript
var middleNode = function(head) {
  let count = 0
  let p = head
  const hash = {}
  while (p) {
      count++
      const node = { next: p}
      hash[count] = node
      p = p.next
  }
  const mid = count % 2 ? Math.floor(count / 2) + 1 : count / 2 + 1
  return hash[mid].next
};

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

技术文档集合