fromtypingimportOptionaldefaddTwoNumbers(l1:Optional[ListNode],l2:Optional[ListNode])->Optional[ListNode]:"""
Adds two numbers represented as linked lists.
Args:
l1 (Optional[ListNode]): The head of the first linked list.
l2 (Optional[ListNode]): The head of the second linked list.
Returns:
Optional[ListNode]: The head of the resulting linked list representing the sum.
Examples:
>>> l1 = ListNode(2)
>>> l1.next = ListNode(4)
>>> l1.next.next = ListNode(3)
>>> l2 = ListNode(5)
>>> l2.next = ListNode(6)
>>> l2.next.next = ListNode(4)
>>> result = addTwoNumbers(l1, l2)
>>> while result:
... print(result.val, end=' ')
... result = result.next
7 0 8
"""initial_node=current_node=ListNode()carry_over=0whilel1orl2:ifl1isNone:x=0y=l2.vall2=l2.nextelifl2isNone:x=l1.valy=0l1=l1.nextelse:x,y=l1.val,l2.vall1,l2=l1.next,l2.next# Creating new node_sum=x+y+carry_overcurrent_node.next=ListNode(val=_sum%10)# Setting up next iterationcarry_over=1if_sum>9else0current_node=current_node.nextifcarry_over>0:current_node.next=ListNode(val=carry_over)returninitial_node.next