迭代
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode h1 = l1, h2 = l2, dummy = new ListNode(-1, h1), d = dummy;
int carry = 0, sum = 0;
while(h1 != null && h2 != null){
sum = h1.val + h2.val + carry;
carry = sum / 10;
h1.val = sum % 10;
d.next = h1;
d = d.next;
h1 = h1.next;
h2 = h2.next;
}
while(h1 != null){
sum = h1.val + carry;
carry = sum / 10;
h1.val = sum % 10;
d.next = h1;
d = d.next;
h1 = h1.next;
}
while(h2 != null){
sum = h2.val + carry;
carry = sum / 10;
h2.val = sum % 10;
d.next = h2;
d = d.next;
h2 = h2.next;
}
if(carry != 0){
d.next = new ListNode(carry);
}
return dummy.next;
}
}
递归
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return addTwoNumbers(l1, l2, 0);
}
ListNode addTwoNumbers(ListNode l1, ListNode l2, int carry) {
if(l1 == null && l2 == null){
if(carry != 0) return new ListNode(carry);
else return null;
}
if(l1 == null) {
int sum = l2.val + carry;
l2.val = sum % 10;
carry = sum / 10;
l2.next = addTwoNumbers(null, l2.next, carry);
return l2;
}
if(l2 == null){
int sum = l1.val + carry;
l1.val = sum % 10;
carry = sum / 10;
l1.next = addTwoNumbers(l1.next, l2, carry);
return l1;
}
int sum = l1.val + l2.val + carry;
l1.val = sum % 10;
carry = sum / 10;
l1.next = addTwoNumbers(l1.next, l2.next, carry);
return l1;
}
}