* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode resultList = null;
ListNode resultNode = null;
ListNode resultNext = null;
int carry = 0;
while(l1 != null && l2 != null) {
resultNext = new ListNode(l1.val + l2.val + carry);
carry = resultNext.val / 10;
resultNext.val = resultNext.val % 10;
if (resultList == null) {
resultNode = resultNext;
resultList = resultNext;
} else {
resultNode.next = resultNext;
resultNode = resultNext;
}
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
resultNext = new ListNode(l1.val + carry);
carry = resultNext.val / 10;
resultNext.val = resultNext.val % 10;
resultNode.next = resultNext;
resultNode = resultNext;
l1 = l1.next;
}
while (l2 != null) {
resultNext = new ListNode(l2.val + carry);
carry = resultNext.val / 10;
resultNext.val = resultNext.val % 10;
resultNode.next = resultNext;
resultNode = resultNext;
l2 = l2.next;
}
if (carry > 0) {
resultNext = new ListNode(carry);
resultNode.next = resultNext;
}
return resultList;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return addList(l1, l2, 0);
}
public ListNode addList(ListNode l1, ListNode l2, int carry){
if(l1 == null && l2 == null){
return carry == 0? null : new ListNode(carry);
}
if(l1 == null && l2 != null){
l1 = new ListNode(0);
}
if(l2 == null && l1 != null){
l2 = new ListNode(0);
}
int sum = l1.val + l2.val + carry;
ListNode curr = new ListNode(sum % 10);
curr.next = addList(l1.next, l2.next, sum / 10);
return curr;
}
}