File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ # class ListNode:
3
+ # def __init__(self, val=0, next=None):
4
+ # self.val = val
5
+ # self.next = next
6
+ class Solution :
7
+ def mergeKLists (self , lists : List [ListNode ]) -> ListNode :
8
+ if not lists or len (lists ) == 0 :
9
+ return None
10
+
11
+ while len (lists ) > 1 :
12
+ mergedLists = []
13
+ for i in range (0 , len (lists ), 2 ):
14
+ l1 = lists [i ]
15
+ l2 = lists [i + 1 ] if (i + 1 ) < len (lists ) else None
16
+ mergedLists .append (self .mergeList (l1 , l2 ))
17
+ lists = mergedLists
18
+ return lists [0 ]
19
+
20
+ def mergeList (self , l1 , l2 ):
21
+ dummy = ListNode ()
22
+ tail = dummy
23
+
24
+ while l1 and l2 :
25
+ if l1 .val < l2 .val :
26
+ tail .next = l1
27
+ l1 = l1 .next
28
+ else :
29
+ tail .next = l2
30
+ l2 = l2 .next
31
+ tail = tail .next
32
+ if l1 :
33
+ tail .next = l1
34
+ if l2 :
35
+ tail .next = l2
36
+ return dummy .next
You can’t perform that action at this time.
0 commit comments