2

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 Answers 3

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

I'm new to java from decades of javascript, this solution really helped me understand how to work with linkLists and a few good java tricks i wouldnt have though of. thanx
1

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;
}

}

3 Comments

Could you please explain the ternary operators? Trying to better understand your logic
As we know every node has a value, l1 == null ? 0 : l1.val if l1 node is null then I'm considering the value as 0 otherwise the l1.val Think for case [1], [1,2,3,4]. After the first iteration, l1 will be null and l2 is now pointing to the 2nd position(2). now we are going to add 0 + 2 and put that to the resulting answer.
l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; if l1 is already null then we don't next to increment/go forward. think about the case I mentioned in the previous comment. on 2nd iteration, l1 is already null so no need to go forward, but for l2 we will go forward (l2.next).
1

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;
}

5 Comments

This will resolve the overriding of the variable head problem. But it will throw a NullPointerExpection if submit on leetCode.
Error for test case like l1 = [9,9,9] and l2 = [9]
edited the answer for solution of the test case. Not clear if the prbl on first comment is the same than second
2nd comment is the test case for the first comment.
i reingeineered the solution and add the management of case of null nodes in input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.