# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defmergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: if list1 isNoneand list2 isNone: returnNone if list1 isNoneand list2 isnotNone: return list2 if list1 isnotNoneand list2 isNone: return list1
if list1.val <= list2.val: ans = ListNode(list1.val) list1 = list1.next else: ans = ListNode(list2.val) list2 = list2.next
current = ans while list1 and list2: if list1.val <= list2.val: new_node = ListNode(list1.val) current.next = new_node list1 = list1.next else: new_node = ListNode(list2.val) current.next = new_node list2 = list2.next current = current.next if list1: current.next = list1 if list2: current.next = list2 return ans