I am trying to sum 2 linked lists, element by element, the result will be put into a new list.
Example :
Input : list1 : 5->3->4
list2 : 6->1->2
Output : list3 : 11->4->6
Here's what i've done so far :
internal class Program
{
static void Main(string[] args)
{
ListNode l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(3);
ListNode l2 = new ListNode(1);
l2.next = new ListNode(2);
l2.next.next = new ListNode(3);
ListNode l3 = new ListNode();
while (l1 != null && l2 != null)
{
l3.val += l1.val + l2.val;
l1 = l1.next;
l2 = l2.next;
l3.next = new ListNode();
}
while(l3 != null)
{
Console.WriteLine(l3.val + " ->");
l3 = l3.next;
}
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
}
My code sums up the lists, but not for each element, for example the output for the above code is list3 : 12->0. Any ideea why is this happening?