42.6. Python programming introduction#

42.6.1. Merge two ascending lists into a new ascending list and returns.#

from typing import List, Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
    if not l1: return l2  
    if not l2: return l1
    if l1.val <= l2.val:
        l1.next = mergeTwoLists(l1.next,l2)
        return l1
    else:
        l2.next = mergeTwoLists(l1,l2.next)
        return l2
    

l1 = ListNode(0)
l1.next = ListNode(2)
l1.next.next = ListNode(4)

l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)

merged_list = mergeTwoLists(l1.next, l2)

assert merged_list.val == 1
assert merged_list.next.val == 2
assert merged_list.next.next.val == 3
assert merged_list.next.next.next.val == 4
assert merged_list.next.next.next.next.val == 4
assert merged_list.next.next.next.next.next == None