Give two non-empty linked lists to represent two non-negative integers. Their respective bits are stored in reverse order, and each node can store only one digit.

If we add these two numbers together, a new linked list is returned to represent their sum.

You can assume that neither of these numbers will start with 0, except for the number 0.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Cause: 342 + 465 = 807

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; }} * * /
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        /** if the next node of the long contact is empty, return if the next node of the long contact is empty. If the next node of the long contact is empty, return if the next node of the long contact is empty. When returning, it is necessary to determine whether the last node plus the preceding digit should be carried backward. If so, it is necessary to create a new node and return at the end. * * /
        ListNode l11 = l1;
        ListNode l22 = l2;
        int number=0;
        int i = 0 , j = 0;
        // Execute as long as one of the lists is not empty
        while(l11! =null|| l22! =null) {if(l11==null&& l22! =null){
                number = number + l22.val;
                l22.val = number%10;
                number = (int)number/10;
                i++;
                if(l22.next==null && number==1){
                    ListNode last = new ListNode(number);
                    l22.next = last;
                    return l2;
                }
                l22 = l22.next;
                System.out.print(number);
                
            }
            if(l11! =null && l22==null) {
                number = number + l11.val;
                l11.val = number%10;
                number = (int)number/10;
                if(l11.next==null && number==1){
                    ListNode last = new ListNode(number);
                    l11.next = last;
                    return l1;
                }
                l11=l11.next;
                j++;              
            }
            if(l11! =null&& l22! =null) {
                number = number + l11.val+ l22.val;
                l11.val = number%10;
                l22.val = number%10;
                number = (int)number/10;
                
                if(l11.next==null && l22.next==null && number==1){
                    ListNode last = new ListNode(number);
                    l11.next = last;
                    returnl1; } l11 = l11.next; l22 = l22.next; }}returni>j? l2: l1; }}Copy the code