# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head1 ListNode类 
# @param head2 ListNode类 
# @return ListNode类
#
class Solution:
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        if not head1:#head1不存在(为None),直接返回head2
            return head2
        if not head2:#head2不存在(为None),直接返回head1
            return head1

        s1, s2 = [], []#用两个数组分别存储两个链表的值
        while head1:
            s1.append(head1.val)
            head1 = head1.next
        while head2:
            s2.append(head2.val)
            head2 = head2.next

        head, dec = None, 0#新链表起始节点,进位标记
        while s1 or s2:#根据两个链表的值,生成新的链表
            if not s1:
                s = dec+s2.pop()
            elif not s2:
                s = dec+s1.pop()
            else:
                s = dec+s1.pop()+s2.pop()
            dec, val = divmod(s,10)
            p = ListNode(val)
            p.next = head
            head = p
        if dec:#处理进位
            p = ListNode(dec)
            p.next = head
            head = p

        return head#返回新链表