import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        if(head1==null) return head2;
        if(head2==null) return head1;
        ListNode newHead1  = reverse(head1);
        ListNode newHead2  = reverse(head2);
//         Deque<Integer> stack1 = new LinkedList<>();
//         Deque<Integer> stack2 = new LinkedList<>();
//         while(head1 != null){
//             stack1.push(head1.val);
//             head1 = head1.next;
//         }
//         while(head2 != null){
//             stack2.push(head2.val);
//             head2 = head2.next;
//         }
        int jin = 0 , yushu = 0 ;
        ListNode tmp = new ListNode(-1);
        ListNode head = tmp;
        while(newHead1 != null || newHead2 != null){
            int value1 = newHead1 == null ? 0 : newHead1.val;
            int value2 = newHead2 == null ? 0 : newHead2.val;
            yushu = (value1 + value2 + jin)%10;
            jin = (value1 + value2 + jin)/10;
            tmp.next = new ListNode(yushu);
            tmp = tmp.next;
            if(newHead1 != null){newHead1 = newHead1.next;}
            if(newHead2 != null){newHead2 = newHead2.next;}
        }

        if(jin != 0){
            tmp.next = new ListNode(jin);
        }

        return reverse(head.next);
    }
    public ListNode reverse(ListNode head){
        ListNode pre = null,cur = head, nxt = head;
        while(cur!=null){
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}