user3591092
user3591092

Reputation: 29

java function to find the sum of two lists

everybody

I wrote a code to solve this problem :

Write a Java function Sum2List that takes two lists L1 and L2 of the same size and returns list L that contains the sum of data inside the corresponding nodes of lists L1 and L2

ex : l1 = {1,2,3}
 l2 = {4,5,6}
 l = l1 + l2 => {5,7,9}

my code is :

public class Test {

public static List Sum2List (List l1 , List l2){

List l = new List();
ListNode lNode = new ListNode(0,null);
l.first = lNode;

ListNode p = l1.first;
ListNode q = l2.first;

for (p = l1.first; p.next!=null; p=p.next,q=q.next){

    lNode.data = p.data + q.data;

    if (p.next != null)
        lNode.next = new ListNode(0,null);

}

return l;
}

public static void main (String[] args){

List l1= new List();
ListNode node4 = new ListNode(4,null);
ListNode node3 = new ListNode(3,node4);
ListNode node2 = new ListNode(2,node3);
ListNode node1 = new ListNode(1,node2);

l1.first = node1;

List l2= new List();
ListNode node8 = new ListNode(8,null);
ListNode node7 = new ListNode(7,node8);
ListNode node6 = new ListNode(6,node7);
ListNode node5 = new ListNode(5,node6);

l2.first = node5;

List l = Sum2List(l1,l2);

for(ListNode p = l.first; p.next !=null; p=p.next){
    System.out.println(p.data);
}
}   
}

The problem is that the output is ( 10 ) , While it must be a list contain => 5,7,9

So , where is the mistake in the code ??

Upvotes: 0

Views: 180

Answers (2)

Alexis C.
Alexis C.

Reputation: 93842

The problem is that you don't add any new node in the list you return. You're always modifying the data of the first node.

Currently your method was summing the datas of the second to last node of both lists, so the list you returned only contains one node with the sum of 3 and 7 (=10).

You need to create a new node at each iteration and update the next node of the previous one. So something like this:

for (p = l1.first; p != null; p = p.next, q = q.next){
    lNode.data = p.data + q.data;
    ListNode temp = new ListNode(0, null);
    lNode.next = temp;
    lNode = temp;
}

Also note that you should modify the for condition to be p!=null, otherwise you won't iterate through the last node.

If you walked through your code with a debugger (or with pen and paper!), you would solve this in less time than posting the question here.

Upvotes: 2

Matt Stevens
Matt Stevens

Reputation: 1114

You are not stepping into the new node.

for (p = l1.first; p.next!=null; p=p.next,q=q.next){

    lNode.data = p.data + q.data;

    if (p.next != null){
        lNode.next = new ListNode(0,null);

        lNode = lNode.next;
    }
}

Add the line lNode = lNode.next; and the braces around the if block.

Without running it, I'm not sure if thats the whole problem, but its certainly part of it

Upvotes: 0

Related Questions