---
description: LeetCode 23
---

# Linked List - Merge k Sorted Lists

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

from queue import PriorityQueue

class Solution:
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """

        que = PriorityQueue()
        count = 0
        node = None           
        for node in lists:
            while node:
                # python 3.x 後 PriorityQueue 改成利用 obj1 < obj2 來比較大小
                # 而非 cmp(ob1, ob2), 此舉導致物件與物件無法比大小
                # 為了解決這種狀況, 需加入一中間元素
                ( priority, *可以用來判別大小的元素 e.g. count*, task) 
                que.put((-node.val, count, node))           
                count = count + 1
                node = node.next
        
        next_node = None        
        while not que.empty():         
            node = que.get()[2]
            node.next = next_node
            next_node = node
        return node 
```
