/**
 * 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* reList(ListNode* head) {
        if (!head)return NULL;
        ListNode* pre = NULL;
        ListNode* cur = head;
        while (cur) {
            ListNode* tem = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tem;
        }
        return pre;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if (!head1)return head2;
        if (!head2)return head1;
        ListNode* rhead1 = reList(head1);
        ListNode* rhead2 = reList(head2);
        ListNode* anshead = new ListNode(0);
        ListNode* p = anshead;
        int tem=0;
        while (rhead1 || rhead2) {
            int val = tem;
            if(rhead1)
            {
                val = val + rhead1->val;
                rhead1 = rhead1->next;
            }
            if(rhead2)
            {
                val = val + rhead2->val;
                rhead2 = rhead2->next; 
            }
            tem = val/10;
            p->next = new ListNode(val%10);
            p = p->next;
        }
        if(tem > 0)
        p->next = new ListNode(tem);

        return reList(anshead->next);
    }
};