"""
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
"""
from ListNode import ListNode
from PrintNode import PrintList
def mergeKLists(node):
temp = ListNode(0)
for i in range(len(node)):
temp.next = mergeTwoLists(temp.next, node[i])
return temp.next
def mergeTwoLists(node1, node2):
if node1 is None:
return node2
elif node2 is None:
return node1
if node1.val < node2.val:
node1.next = mergeTwoLists(node1.next, node2)
return node1
else:
node2.next = mergeTwoLists(node1, node2.next)
return node2
node1 = ListNode(1)
node2 = ListNode(3)
node3 = ListNode(5)
node4 = ListNode(2)
node5 = ListNode(4)
node6 = ListNode(6)
node7 = ListNode(7)
node8 = ListNode(8)
node9 = ListNode(9)
node1.next = node2
node2.next = node3
node4.next = node5
node5.next = node6
node6.next = node7
node8.next = node9
lis = [node1, node4, node8]
PrintList(mergeKLists(lis))
23_合并k个排序链表
最新推荐文章于 2023-07-22 16:11:24 发布