1919#Output: 1->1->2->3->4->4->5->6
2020class Solution :
2121 def mergeKLists (self , lists ):
22- tmp = [] #Initialize tmp empty list
23- dummy = head = ListNode (0 ) #Initialize dummy linkedlist
24- for i in lists : #Loop through lists
25- while i : #Loop
26- tmp .append (i .val ) #Append values in tmp list
27- i = i .next #Traverse through list
28- for i in sorted (tmp ): #Loop through sorted tmp list
29- dummy .next = ListNode (i ) #Add the values in dummy linkedlist
30- dummy = dummy .next #Point reference to next node
31- return head .next #Return our sorted dummy list
22+ if not lists : #Condition-check: If list is empty
23+ return #Return Empty
24+ if len (lists ) == 1 : #Condition-check: If list has length of 1
25+ return lists [0 ] #Return that element
26+ mid = len (lists ) // 2 #Initialize mid point
27+ left = self .mergeKLists (lists [:mid ]) #Initialize left by 0 to mid point
28+ right = self .mergeKLists (lists [mid :]) #Initialize right by mid point to last
29+ return self .merge (left , right ) #Return sorted list by using helper method
30+ def merge (self , list1 , list2 ): #Defining method merge that takes two list
31+ tmp = dummy = ListNode (0 ) #Initialize tmp and dummy which are empty linkedlist
32+ while list1 and list2 : #Loop: List 1 and List 2 are not empty
33+ if list1 .val <= list2 .val : #Condition-check: If list1.val is less than or equal to list2.val
34+ tmp .next = ListNode (list1 .val ) #Update the linkedlist by adding value of list1
35+ tmp = tmp .next #Traverse through tmp
36+ list1 = list1 .next #Traverse through list1
37+ else : #Condition-check: Else
38+ tmp .next = ListNode (list2 .val ) #Update the linkedlist by adding value of list2
39+ tmp = tmp .next #Traverse through tmp
40+ list2 = list2 .next #Traverse through list2
41+ if list1 : #Condition-check: If list1 is empty
42+ tmp .next = list1 #Change the point to list1
43+ else : #Condition-check: Else
44+ tmp .next = list2 #Change the point to list2
45+ return dummy .next #Return the dummy linkedlist
0 commit comments