# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    # time O(N) space O(1)
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        carry = 0
        # create dummy node and a pointer, point at dummy node, use ptr to add new nodes after dummy node 
        dummy = ptr = ListNode(0)
        # end condition: l1 and l2 both reached end of list and there is nothing in the caryy 
        while l1 or l2 or carry:
            # initialize v1,v2 first in case either l1,l2 has reached end 
            v1=v2=0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            #caculate sum of v1,v2,caryy; get the remainer of the sum and carry number 
            temp = v1 + v2 + carry
            carry = temp // 10
            temp %= 10
            # create a new ListNode and assign it to ptr.next
            ptr.next = ListNode(temp)
            ptr = ptr.next
        return dummy.next