Java solution with explanation.

  • 0

    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



    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;
            if(l2 != null){
                res += l2.val;
                l2 =;
            ListNode anode = new ListNode(res%10);
   = anode;
            head =;
            res = res/10;


Log in to reply

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