题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
# from sys import _current_frames # from numpy import char # class ListNode: # from numpy import sort # 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 # 解题思路:先把链表合并,然后对合并后的链表进行排序 # 创建新链表 new_list = ListNode(-1) add_list = new_list for chl_list in lists: add_list.next = chl_list while add_list.next: add_list = add_list.next sort_list = new_list.next # 使用冒泡排序 因为简单 while sort_list: char_list = sort_list.next while char_list: if sort_list.val > char_list.val: tmp_val = sort_list.val sort_list.val = char_list.val char_list.val = tmp_val char_list = char_list.next sort_list = sort_list.next return new_list.next