Java solution with explanation.


  • 0
    L

    As for the problem, the length of two linked list are not guaranteed to be the same.
    so in the while loop. "||" is used in order to go through all the nodes in both lists.
    the additional condition is that what i added after the OJ throws out a error as for

    5->null
    5->null
    

    ------------
    0->1->null;

    without the additional condition, 0->null will return, which is definitely not correct.

    In each loop, res gets values from both lists(),
    res % 10 returns the digit value for current position;
    res/10 returns the value which is called carry used for the calculation for the next position.

    Hope it may help you.

    '''
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode head = dummy;
    int res =0;
    while(l1 != null || l2 != null|| res != 0){

            if(l1 != null){
                res += l1.val;
                l1= l1.next;
            }
            if(l2 != null){
                res += l2.val;
                l2 = l2.next;
            }
            ListNode anode = new ListNode(res%10);
            head.next = anode;
            head = head.next;
            res = res/10;
            
        }
        return dummy.next;
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.