请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

正在回答 回答被采纳积分+3

插入代码

1回答

PegasusWang 2019-03-19 23:24:24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
https://leetcode.com/problems/merge-k-sorted-lists/
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
 
Example:
 
Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
"""
 
 
from heapq import heappop, heapify
# Definition for singly-linked list.
 
 
class ListNode:
    def __init__(self, x, next=None):  # 注意我这里next参数
        self.val = x
        self.next = next
 
 
class Solution:
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        = []
        for node in lists:
            while node:
                h.append(node.val)
                node = node.next
 
        if not h:  # 注意这里的边界值 [[]]
            return None
        heapify(h)   # inplace 建堆
        root = ListNode(heappop(h))
        curnode = root
 
        while h:
            nextnode = ListNode(heappop(h))
            curnode.next = nextnode
 
            curnode = nextnode
 
        return root
 
 
def to_list(head):
    """list to []"""
    res = []
    curnode = head
    while curnode:
        res.append(curnode.val)
        curnode = curnode.next
    return res
 
def test_merge():
    l1 = ListNode(1, ListNode(4, ListNode(5)))  # 1->4->5
    l2 = ListNode(1, ListNode(3, ListNode(4)))  # 1->3->4
    = Solution()
    lists = [l1, l2]
    head = s.mergeKLists(lists)
    print(to_list(head))
 
if __name__ == '__main__':
    test_merge()


0 回复 有任何疑惑可以回复我~
  • 你可以通过实例化 ListNode 的定义来定义一个链表。
    l1 = ListNode(1, ListNode(4, ListNode(5)))  # 1->4->5
    回复 有任何疑惑可以回复我~ 2019-03-20 00:01:54
问题已解决,确定采纳
还有疑问,暂不采纳
Python工程师面试宝典 一线大厂资深面试官亲授
  • 参与学习       1034    人
  • 解答问题       102    个

Python工程师面试必看,资深面试官亲授,倍增面试成功率

了解课程
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号