LeetCode23 猴子补丁

本题并不难,但是使用heapq遇到一个问题,python3中如果类没有实现__lt__方法就不能进行比较,所以如果没有等号之间那段代码的话会报错TypeError: '<' not supported between instances of 'ListNode' and 'ListNode',leetcode的ListNode类已经固定了,不能在上面直接加方法,于是打个猴子补丁搞定。

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

class Solution:
    def mergeKLists(self, lists):
		#=================================
        def com_list_node(a,b):
            return a.val < b.val
        ListNode.__lt__ = com_list_node
		#=================================
        import heapq
        h = []
        for i in lists:
            if i:
                heapq.heappush(h, i)
        curr = head = ListNode(-1)
        while h:
            temp = heapq.heappop(h)
            curr.next = temp
            curr = curr.next
            if temp.next:
                heapq.heappush(h,temp.next)
        return head.next
发布了66 篇原创文章 · 获赞 21 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_35753140/article/details/89401625