1.题目

【LeetCode】876.链表的中间节点_leetcode

2.分析

使用fast.next 的状态来判断链表的总结点个数是奇数个还是偶数个。

  • 如果是偶数个节点,那么fast.next 一定不是None,此时返回slow.next
  • 如果是奇数个节点,那么fast.next 一定是None,此时返回slow

3. 代码

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = head

while (fast.next and fast.next.next):
slow = slow.next
fast = fast.next.next

if fast.next and fast.next.next is None:
return slow.next
return