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 ??
ListandListNode? The standardListis an interface, such thatnew List()is not possible. Post complete code.