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 [Optional [ListNode ]]) -> Optional [ListNode ]:
8
+ if not lists : return None
9
+ while len (lists ) > 1 :
10
+ m_list = []
11
+
12
+ for i in range (0 , len (lists ), 2 ):
13
+ h1 = lists [i ]
14
+ h2 = lists [i + 1 ] if (i + 1 ) < len (lists ) else None
15
+
16
+ m_list .append (self .mergeTwoLists (h1 , h2 ))
17
+ lists = m_list
18
+ return lists [0 ]
19
+
20
+
21
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
22
+ dummy = ListNode ()
23
+ tail = dummy
24
+ while list1 and list2 :
25
+ if list1 .val < list2 .val :
26
+ tail .next = list1
27
+ list1 = list1 .next
28
+ else :
29
+ tail .next = list2
30
+ list2 = list2 .next
31
+ tail = tail .next
32
+ if list1 :
33
+ tail .next = list1
34
+ elif list2 :
35
+ tail .next = list2
36
+ return dummy .next
You can’t perform that action at this time.
0 commit comments