原题:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
分析:
这道题与上一个合并两个有序链表的题相似,可以直接利用上次做的那个,两两排序即可
代码:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
t11 = l1
t22 =l2
while t11.next!=None:
t11 = t11.next
t11.next = ListNode(-1)
while t22.next!=None:
t22 = t22.next
t22.next = ListNode(-1)
t1 = l1
t2 = l2
self=ListNode(0)
t3 = self
while ((t1.val !=-1)&(t2.val!=-1)):
if t1.val<t2.val:
t3.next = ListNode(t1.val)
t1 = t1.next
t3 = t3.next
else:
t3.next = ListNode(t2.val)
t2 = t2.next
t3 = t3.next
if t1.val!=-1:
t3.next = t1
else:
t3.next=t2
return self.next
self =ListNode(0)
l1 = ListNode(1)
l1.next = ListNode(4)
l1.next.next = ListNode(5)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
l3=ListNode(2)
l3.next=ListNode(6)
test = mergeTwoLists(self,l1,l2)
test1 = mergeTwoLists(self,test,l3)
while test1.next!=None:
print(test1.val)
test1 = test1.next
效果:
另外,可以实用优先队列:
代码:
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
head = point = ListNode(0)
q = PriorityQueue()
for l in lists:
if l:
q.put((l.val, l))
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
```
效果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190907152555972.png)