21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.



def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]):
               
    p1, p2 = list1, list2
    head = ListNode()
    cur = head
   
    while p1 and p2:
       
        if p1.val <= p2.val:                                
            cur.next = p1
            p1 = p1.next
        else:
            cur.next = p2
            p2 = p2.next
           
        cur = cur.next
               
    cur.next = p2 if p1 is None else p1        
       
    return head.next

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break