leetcode 876 链表的中间结点 python实现

还是比较简单的题,但第一次使用的方法还是超时了,当时使用了两个while,太low了

之后想到了使用字典的方法,一定要擅长使用字典啊!

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
import math
class Solution:
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 首先要知道链表一共有多少个结点
        count = 0
        res = {}
        while head != None:
            count += 1
            res[count] = head
            head = head.next
        #j = math.ceil(count/2)
        #if count % 2 == 0:
        #    return res[j+1]
        #else:
        #    return res[j]
        j = math.ceil((count-1)/2) + 1
        return res[j]
       

猜你喜欢

转载自blog.csdn.net/weixin_41722370/article/details/83314501