# 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:
        # 反转链表的辅助函数
        def reverse_list(head):
            prev = None
            while head:
                next_node = head.next
                head.next = prev
                prev = head
                head = next_node
            return prev

        # 反转两个输入链表
        head1 = reverse_list(head1)
        head2 = reverse_list(head2)

        carry = 0
        result_head = None

        # 相加链表节点
        while head1 or head2 or carry:
            sum_value = carry
            if head1:
                sum_value += head1.val
                head1 = head1.next
            if head2:
                sum_value += head2.val
                head2 = head2.next

            carry = sum_value // 10
            new_node = ListNode(sum_value % 10)
            new_node.next = result_head
            result_head = new_node

        return result_head