
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if list1 == None and list2 == None:
return None
elif list1==None and list2!=None:
return list2
elif list1!=None and list2==None:
return list1
elif (list1.val<=list2.val):
head = list1
list1= list1.next
else:
head = list2
list2= list2.next
walk = head
while(list1!=None and list2!=None):
if list1.val <= list2.val:
walk.next = list1
walk = walk.next
list1 = list1.next
else:
walk.next = list2
walk = walk.next
list2 = list2.next
if list1!=None:
walk.next = list1
elif list2 != None:
walk.next = list2
else:
walk.next = None
return head
