//翻转两个链表过后以大数相加的套路处理,然后把结果链表在翻转一次就好了
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
        ListNode newhead1=rev(head1);
        ListNode newhead2=rev(head2);
        ListNode ans=new ListNode(-1);
        ListNode res=ans;
        if(newhead1==null)
            return newhead2;
        if(newhead2==null)
            return newhead1;
        int jwei=0;
        while(newhead1!=null&&newhead2!=null){
            int num=newhead1.val+newhead2.val+jwei;
            jwei=num/10;
              num%=10;
            ListNode cur=new ListNode(num);
            ans.next=cur;
            ans=ans.next;
            newhead1=newhead1.next;
            newhead2=newhead2.next;
        }
        while(newhead2!=null){
            int num=newhead2.val+jwei;
            jwei=num/10; 
            num%=10;
            ListNode cur=new ListNode(num);
            ans.next=cur;
            ans=ans.next;
            newhead2=newhead2.next;
        }
                while(newhead1!=null){
            int num=newhead1.val+jwei;
            jwei=num/10; 
            num%=10;
            ListNode cur=new ListNode(num);
            ans.next=cur;
            ans=ans.next;
            newhead1=newhead1.next;
        }
        if(jwei!=0){
            ListNode cur=new ListNode(jwei);
            ans.next=cur;
        }
       return rev(res.next);
    }
    
    public ListNode rev(ListNode head){
        ListNode cur=null;
        while(head!=null){
            ListNode temp=head.next;
            head.next=cur;
            cur=head;
            head=temp;
        }
        return cur;
    }
}