/*
 * 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  && head2 == null){
            return null;
        }
        if(head1 == null){
            return head2;
        }
        if(head2 == null){
            return head1;
        }
        head1 = reverse(head1);
        head2 = reverse(head2);
        //开始从最右侧 个位相加了
        int addition = 0;
        ListNode head = new ListNode(-1);
        ListNode current = head;
        while(head1 != null || head2 != null){
            int a = 0, b = 0;
            if(head1 != null){
                a = head1.val;
                head1 = head1.next;
            }
            
            if(head2 != null){
                b = head2.val;
                head2 = head2.next;
            }
            int sum = a + b +addition;
            current.val = sum % 10;
            addition = sum / 10;
            ListNode next = new ListNode(-1);
            current.next =  next;
            current = next;
        }
        current.val = addition;
        head = reverse(head);
        if(head.val == 0){
            head = head.next;
        }
        return head;
    }
        private ListNode reverse(ListNode head){
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}