题解 | #合并k个已排序的链表#

合并k个已排序的链表

http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

优先队列,队列里存放(node.val, node)的pair

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param lists ListNode类一维数组 
# @return ListNode类
#
from Queue import PriorityQueue
class Solution:
    def mergeKLists(self , lists ):
        # write code here
        q = PriorityQueue()
        for l in lists:
            if l:
                q.put((l.val, l))
        head = ListNode(0)
        point = head
        while not q.empty():
            val, node = q.get()
            point.next = ListNode(val)
            point = point.next
            node = node.next
            if node:
                q.put((node.val, node))
        return head.next

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务