题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
from operator import le # 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: # 特殊情况特殊处理 if len(lists)==0: return None if len(lists)==1: return lists[0] mid=len(lists)//2 left =self.mergeKLists(lists[:mid]) right=self.mergeKLists(lists[mid:]) ## 下面就是合并两个有序链表的代码了。 dummy=ListNode(-1) curr=dummy while left and right: if left.val < right.val: curr.next=left left=left.next else: curr.next=right right=right.next curr=curr.next if left==None: curr.next = right else: curr.next = left curr = dummy.next return dummy.next