Skip to content

Commit 94a59d8

Browse files
committedJan 30, 2024
[23] [Time Beats: 98.49%] [Memory Beats: 51.27%] - LeetPush
1 parent 32df494 commit 94a59d8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 

‎23-Merge-k-Sorted-Lists.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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

0 commit comments

Comments
 (0)
Please sign in to comment.