import java.util.*;
public class Solution {
    public ListNode addInList (ListNode head1, ListNode head2) {
        head1 = reverseList(head1);
        head2 = reverseList(head2);
        int carry = 0;
        ListNode dumpy = new ListNode(-1);
        ListNode cur = dumpy;
        while(head1!=null || head2!=null || carry!=0){
            int x = 0;
            int y = 0;
            if(head1!=null){
                x = head1.val;
                head1 = head1.next;
            }
            if(head2!=null){
                y = head2.val;
                head2 = head2.next;
            }
            int sum = x+y+carry;
            carry = sum/10;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
        }
        return reverseList(dumpy.next);
    }

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