23. Merge k Sorted Lists
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: List[ListNode], l2: List[ListNode]) -> ListNode:
curr = head = ListNode()
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if not l2:
curr.next = l1
if not l1:
curr.next = l2
return head.next
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
for i in range(1, len(lists)):
l1 = lists[i-1]
l2 = lists[i]
lists[i] = self.mergeTwoLists(l1, l2)
return lists[-1]Head
Last updated