/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if(!head1) return head2;
        if(!head2) return head1;
        head1=reverseList(head1);
        head2=reverseList(head2);
        int carry=0;
        auto ResHead=new ListNode(0);
        auto iterator=ResHead;
        while(head1 || head2){
            int val1=0;
            if(head1) val1=head1->val;
            int val2=0;
            if(head2) val2=head2->val;
            iterator->val=(val1+val2+carry)%10;
            carry=(val1+val2+carry)/10;
            if(head1)
            head1=head1->next;
            if(head2)
            head2=head2->next;
            if(head1|| head2 || carry){
                iterator->next=new ListNode(0);
                iterator=iterator->next;
            }
        }
        if(carry) iterator->val=carry;
        return reverseList(ResHead);
    }
  //reverseList反转链表
    ListNode* reverseList(ListNode* root){
        ListNode* cur=root;
        ListNode* pre=nullptr;
        while(cur != nullptr){
            //断开链表,要记录后续一个
            // std::cout<<cur->val<<" ";
            ListNode* temp = cur->next;
            //当前的next指向前一个
            cur->next = pre; 
            //前一个更新为当前
            pre = cur; 
            //当前更新为刚刚记录的后一个
            cur = temp;
        }
        printList(pre);
        return pre;
    }
  //printList打印链表
    void printList(ListNode* head) {
        while (head != nullptr) {
            std::cout << head->val << " ";
            head = head->next;
        }
        std::cout << std::endl;
    }
};