#!/usr/bin/env python3

__author__ = 'Wei Mu'

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        
        current_node = ListNode(0)
        ans = current_node
        
        add_one = 0
        num1 = num2 = 0
        
        l1_end = False
        l2_end = False
        
        while l1_end != True or l2_end != True or add_one != 0:
            # Condition when one list reached the end
            if l1_end == True and l2_end == True:
                pass
            elif l1_end == True and l2_end == False:
                num2 = l2.val
            elif l2_end == True and l1_end == False:
                num1 = l1.val
            else:
                num1 = l1.val
                num2 = l2.val
            
            # print(num1, num2)
            
            # Routine update
            sum_up = num1 + num2 + add_one
            add_one, digit  = divmod(sum_up, 10)
            
            next_node = ListNode(digit)
            current_node.next = next_node
            current_node = current_node.next
                
            
            # Update if the next element reached the end
            if l1.next == None and l2.next == None:
                l1_end = True
                l2_end = True
                num1 = 0
                num2 = 0
            elif l1.next == None and l2.next != None:
                l1_end = True
                num1 = 0
                l2 = l2.next
            elif l2.next == None and l1.next != None:
                l2_end = True
                num2 = 0
                l1 = l1.next
            else:
                l1 = l1.next
                l2 = l2.next
                            
        return ans.next
            
        
        
