2
votes

I am solving this question on Leetcode. However, I have an issue with returning inked list.

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

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

# Singly Linked List  #


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

The issue

At the last part of my code, I realize I am not able to save the inserted numbers in head. I notice that the head.next = new ListNode(sum %10);` is overwriting my node. How do I go about saving the state of my list?

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuilder a = new StringBuilder();
        StringBuilder b = new StringBuilder();
        
        ListNode temp = l1;
        ListNode temp2 = l2;
        while(temp != null || temp2 != null) {
            a.append(temp.val);
            b.append(temp2.val);
            temp = temp.next;
            temp2 = temp2.next;
        }
       int sum =  Integer.parseInt(a.reverse().toString()) +                                                     Integer.parseInt(b.reverse().toString());
   
       ListNode head = new ListNode(0); 
       
        while(sum != 0) {
           head.next = new ListNode(sum % 10);
           head = head.next;
           sum /= 10;
        }
         
        return head;
    }
3

3 Answers

1
votes

The problem is due to the head = head.next; line. This is overwriting the variable head, that's why the program returns always the 'last' node. The solution is to return a different variable. However, there's another problem. I.E. your returned list has always a tailing 0. I.E. for the example imput you give, it returns 0->7->0->8 . This because you always initialize your list to 0. Here a possible (not so elegant, but quick), solution.

EDIT

In order to prevent NullPointerException on lists of different sizes, the generation of the strings is put in a method, called once per list. Added management of case of null node

EDIT 2 Added a reingeneering of functions and the management of cases of null nodes

public String nodeToString(ListNode l){
    StringBuilder a = new StringBuilder();
    ListNode temp = l;
    while(temp != null ) {
        a.append(temp.val);
        temp = temp.next;
        
    }
    return a.reverse().toString();
}

public Integer nodeToInt(ListNode l){
    String a=nodeToString(l);
    Integer ret=0;
    if(a.length()>0)
        ret=Integer.parseInt(a);
    return ret;
}


public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
   Integer a=nodeToInt(l1);
   Integer b=nodeToInt(l2);
   int sum =  a+b;   
   ListNode head = new ListNode(sum % 10); 
   sum /= 10;
   
   ListNode retVal=head;
   
    while(sum != 0) {
       head.next = new ListNode(sum % 10);
       head = head.next;
       sum /= 10;
    }
     
    return retVal;
}
0
votes

We'd use a sentinel node (right before head or start node) for solving this problem. Then, we'd just return sentinel.next; instead of return head;.

This'll pass through:

public final class Solution {
    public static final ListNode addTwoNumbers(
        ListNode l1, 
        ListNode l2
    ) {
        int left = 0;
        ListNode sentinel = new ListNode(0);
        ListNode tail = sentinel;

        while (!(l1 == null && l2 == null && left == 0)) {
            final int add1 = l1 != null ? l1.val : 0;
            final int add2 = l2 != null ? l2.val : 0;
            final int sum = add1 + add2 + left;
            left = sum / 10;
            final ListNode tempNode = new ListNode(sum % 10);
            tail.next = tempNode;
            tail = tempNode;

            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }

        }

        return sentinel.next;
    }
}

References

  • For additional details, please see the Discussion Board which you can find plenty of well-explained accepted solutions in there, with a variety of languages including efficient algorithms and asymptotic time/space complexity analysis1, 2.
0
votes

Why not build the result list while iterating the l1 and l2? We don't need StringBuilder, parseInt or reverse().

Runtime: 1 ms, faster than 100.00% of Java online submissions for Add Two Numbers. Memory Usage: 39.6 MB, less than 75.33% of Java online submissions for Add Two Numbers.

Here is my solution

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode res = new ListNode(0);
    ListNode ret = res;
    int carry = 0;
    while (l1 != null || l2 != null) {
        int a = l1 == null ? 0 : l1.val;
        int b = l2 == null ? 0 : l2.val;
        l1 = l1 == null ? null : l1.next;
        l2 = l2 == null ? null : l2.next;
        res.next = new ListNode((a + b + carry) % 10);
        res = res.next;
        carry = ((a + b + carry) / 10);
    }
    if (carry != 0) res.next = new ListNode(carry);
    return ret.next;
}

}