---
title: leetcode-876
date: 2020-03-26 21:18:41
tags:
categories: leetcode
---

### 876. 链表的中间结点



[题目](https://leetcode-cn.com/problems/middle-of-the-linked-list/)



<!--more-->



思路是遍历一遍得到整个链表，讲每个 node 放进一个 list，就可以通过下标得到中间的。



```python
# Definition for singly-linked list.
class ListNode:
  def __init__(self, x):
    self.val = x
    self.next = None

class Solution:
  def middleNode(self, head: ListNode) -> ListNode:
    l = []
    n = head
    while n.next:
      l.append(n)
      n = n.next
    l.append(n)
    return l[len(l)//2]

 #44 ms	13.7 MB
```



看官方解答，还有一个骚操作，通过两个速度不一样的指针，一个一次走一步，一个两次走一步，快的走到底时，慢的就在中间了。



```python
class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

作者：LeetCode-Solution
链接：https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/lian-biao-de-zhong-jian-jie-dian-by-leetcode-solut/
来源：力扣（LeetCode）
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
```




