public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode p, dummy = new ListNode(0);
p = dummy;
while (l1 != null  l2 != null  carry != 0) {
if (l1 != null) {
carry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
carry += l2.val;
l2 = l2.next;
}
p.next = new ListNode(carry%10);
carry /= 10;
p = p.next;
}
return dummy.next;
}
Java concise solution.


@pricool
ListNode class is pre defined in the question, go back to the question and check the blue part code.
You can find .next and .val field there.

@mr618show Because p will be used to store current digit in loop and the object address stored in p will change. Use dummy to stay at the beginning to identify the head place.

@caikehe This is hilarious! I just answered this question and my answer is almost identical to yours, even down to the naming! GMTA :)


@caikehe
I am wondering why the following code is 1ms slower than your answer. I thought / and % are always slower than + and class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; ListNode p; ListNode dummy = new ListNode(0); p = dummy; while(l1 !=null  l2 != null  carry!=0) { if(l1!=null) { carry +=l1.val; l1 = l1.next; } if(l2!=null) { carry +=l2.val; l2 = l2.next; } if(carry>9) { p.next = new ListNode(carry10); carry = 1; } else { p.next = new ListNode(carry); carry = 0; } p = p.next; } return dummy.next; } }