148. Sort List

Given the head of a linked list, return the list after sorting it in ascending order.

def sortList(self, head: Optional[ListNode]):       
    def find_mid(start): # guaranteed to have two nodes
        slow, fast = start, start            
       
        while fast and fast.next:                
            if slow.next:
                mid_prev = slow
                mid = slow.next               
            slow = slow.next                
            fast = fast.next.next                
                               
        mid_prev.next = None            
        return mid
   
    def merge(a, b):
        dummy = ListNode()
        p = dummy       
        while a and b:
            if a.val < b.val:
                p.next = a
                a = a.next
            else:
                p.next = b
                b = b.next
            p = p.next                       
        p.next = a if a else b                       
        return dummy.next       
    if not head or not head.next:
        return head
   
    mid = find_mid(head)        
    sorted_left  = self.sortList(head)
    sorted_right = self.sortList(mid)      
    return merge(sorted_left, sorted_right) 

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break