合并K个排序链表
题目描述:
合并 k
个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
解题思路:
整体思路与Merge Two Lists相同。就是从原来的两个数中取最小的节点改为从k个数中取最小的节点。
- 可以先进行遍历,将k个链表存储进一个数组
res[]
- 然后对
res[]
数组进行sort()
排序 - 创建临时头结点
first
,然后从res[]
数组中从头一一取出节点,接入新建立的链表中,可以使用pop(0)
函数
Python源码:
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
res = []
for i in lists:
while i:
res.append(i.val)
i = i.next
if not res:
return []
res.sort()
l = ListNode(0)
first = l
while res:
l.next = ListNode(res.pop(0))
l = l.next
return first.next
欢迎关注我的github:https://github.com/UESTCYangHR