876. 链表的中间结点


class Solution(object):
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 用pre记录下头指针的位置,用于第二趟遍历
        pre = head
        num = 0
        # 第一趟遍历统计节点个数
        while head:
            num += 1
            head = head.next
        # round()返回值会四舍五入,符合“中间偏右”
        num = round(num / 2)
        # 第二趟遍历
        while num > 0:
            pre = pre.next
            num -= 1
        return pre
原文地址:https://www.cnblogs.com/panweiwei/p/12857302.html