HTMLify

LeetCode - Merge k Sorted Lists - Python
Views: 6 | Author: abh
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        #if not lists or not all(lists):
        #    return None
        snode = ListNode(None)
        cnode = snode
        while lists:
            while None in lists:
                lists.remove(None)
            if not lists: break
            i = min(range(len(lists)), key=lambda e:lists[e].val)
            cnode.val = lists[i].val
            lists[i] = lists[i].next
            while None in lists:
                lists.remove(None)
            if lists:
                cnode.next = ListNode()
                cnode = cnode.next
        if snode.val is None: return None
        return snode

Comments