题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param lists ListNode类一维数组 # @return ListNode类 # class Solution: def mergeKLists(self , lists: List[ListNode]) -> ListNode: # write code here tmp = [] for head in lists: while head: tmp.append(head.val) head = head.next if not tmp: return None tmp.sort() res = ListNode(-1) cur = res for i in range(len(tmp)): cur.next = ListNode(tmp[i]) cur = cur.next return res.next
辅助队列法:将 ListNode 中的所有 val 取出后进行排序,随后构造一个 新的ListNode