Merge K sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6]
Output:1->1->2->3->4->4->5->6
# Definition for singly-linked list.class listnode:def __init__ (self, x): Self.val = x self.next = Nonec Lass Solution:def mergeklists (self, lists): "" ": Type Lists:list[listnode]: Rtype:listnode "" "If Len (lists) ==0:return None if Len (lists) ==1:return lists[0] Head = s Elf.mergetwolists (lists[0],lists[1]) for I in Range (2,len (lists)): Head = self.mergetwolists (head,lists[ I]) return head def mergetwolists (self, L1, L2): "" ": Type L1:ListNode:type L2:listnode : Rtype:listnode "" "If L1 is none and L2 are none:return L1 if L1 is none: Return L2 if L2 is none:return l1 start = ListNode (0) pos = start while L1 and L2:if L1.val<l2.val:pos.next = L1 L1 = L1.next pos = Pos.nex T else: Pos.next = L2 L2 = L2.next pos = pos.next if l1:pos.next = L1 L1 = L1.next pos = pos.next If L2:pos.next = L2 L2 = L2.next pos = Pos.next return Start.next
. Merge k Sorted Lists