public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(null == l1 ) return l2;
if(null == l2) return l1;
ListNode tempHead = new ListNode(0);
ListNode temp = tempHead;
while(l1!=null  l2!=null){
boolean flag = false;
if(l1!=null){
temp.val = l1.val;
l1 = l1.next;
flag = true;
}
if(l2!=null){
temp.val = temp.val + l2.val;
l2 = l2.next;
flag = true;
}
//temp .next = new ListNode(0);
// temp = temp.next;
}
return tempHead;
}
Does any one know why this fails.


Flag is used to mark if previous nodes' sum is greater than 0 ; In the code flag is set without checking this condition and flag is set but never used.Memory allocation need to be done for all the nodes in the output sum linked list, but in the code space is allocated only for head node. In every iteration of the loop temp node(which stores resultant sum) must be updated with temp.next Please find this below code with modifications
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry =0; ListNode newHead = new ListNode(0); ListNode temp=newHead; while(l1 != null  l2 != null){ if(l1 != null){ carry += l1.val; l1 = l1.next; } if(l2 != null){ carry += l2.val; l2 = l2.next; } temp.next = new ListNode(carry%10); temp = temp.next; carry /= 10; } if(carry==1) temp.next=new ListNode(1); return newHead.next; } }