leetcode----腾讯 合并K个排序链表

原题:
合并 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

聆一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值