题目
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode head = null, cur = null;
int carry = 0;
while (l1 != null || l2 != null) {
if (head == null) {
int tmp = l1.val + l2.val;
head = new ListNode(tmp % 10);
cur = head;
carry = tmp / 10;
l1 = l1.next;
l2 = l2.next;
} else {
int tmp = carry;
if (l1 != null) {
tmp += l1.val;
l1 = l1.next;
}
if (l2 != null) {
tmp += l2.val;
l2 = l2.next;
}
cur.next = new ListNode(tmp % 10);
carry = tmp / 10;
cur = cur.next;
}
}
if (carry > 0) {
cur.next = new ListNode(carry);
}
return head;
}
}