# 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
        cur1 = head1
        cur2 = head2
        pre1 = None
        pre2 = None
        pre = cur = ListNode(0)
        while cur1: #翻转链表1,pre1为翻转后的头指针
            tmp = cur1.next
            cur1.next = pre1
            pre1 = cur1 
            cur1 = tmp
        while cur2:#翻转链表2,pre2为翻转后的头指针
            tmp = cur2.next
            cur2.next = pre2
            pre2 = cur2 
            cur2 = tmp
        cur1 = pre1 #把头指针赋值给cur1
        cur2 = pre2#把头指针赋值给cur2
        c = 0#进位标志
        while cur1 and cur2:
            cur.next = ListNode(0)
            cur.next.val = (cur1.val + cur2.val + c)%10
            cur = cur.next
            c = (cur1.val + cur2.val + c)//10
            cur1 = cur1.next
            cur2 = cur2.next
        while cur1:
            cur.next = ListNode(0)
            cur.next.val = (cur1.val + c)%10
            cur = cur.next
            c = (cur1.val + c)//10
            cur1 = cur1.next
        while cur2:
            cur.next = ListNode(0)
            cur.next.val = (cur2.val + c)%10
            cur = cur.next
            c = (cur2.val + c)//10
            cur2 = cur2.next
        if c == 1 :
            cur.next = ListNode(1) 
        post = None
        cur = pre.next
        while cur:
            tmp = cur.next
            cur.next = post 
            post = cur 
            cur = tmp
        return post