# Help! what's wrong with my code? Add Two Numbers

• ``````public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
int sum = 0;
ListNode ln = null;
while(l1!=null || l2!=null || sum!=0){
sum += l1 == null?0:l1.val;
sum += l2 == null?0:l2.val;
if(sum>=10){
carry = 1;
sum = sum -10;
}
if(ln == null)
ln = new ListNode(sum);
else{
ln.next = new ListNode(sum);
ln = ln.next;
}
if(l1!=null)
l1 = l1.next;
if(l2!=null)
l2 = l2.next;

sum = carry;
carry = 0;
}
ln.next = null;
return ln;
}
``````

}

• ln has been set to its next and next...
Before set ln to its next, you must copy its refrence, Then return the copy.

`````` int carry = 0;
int sum = 0;
ListNode ln = null;
ListNode root = null;
while(l1!=null || l2!=null || sum!=0){
sum += l1 == null?0:l1.val;
sum += l2 == null?0:l2.val;
if(sum>=10){
carry = 1;
sum = sum -10;
}
ln.val = sum;
if(ln == null) {
ln = new ListNode(sum);
root = ln;
}
else{
ln.next = new ListNode(sum);
ln = ln.next;
}
if(l1!=null)
l1 = l1.next;
if(l2!=null)
l2 = l2.next;

sum = carry;
carry = 0;
}
ln.next = null;
return root;``````

• Thank you, I have solved this problem. As you said,I need a refrence targeting at the first of my link list.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.