题目
Python
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
tail = ListNode(-1)
cur = tail
cur1, cur2 = l1, l2
carry = 0
while cur1 != None or cur2 != None or carry:
cur1_val = cur1.val if cur1 else 0
cur2_val = cur2.val if cur2 else 0
sum_val = cur1_val + cur2_val + carry
cur_val = sum_val % 10
carry = sum_val // 10
cur.next = ListNode(cur_val)
cur = cur.next
cur1 = cur1.next if cur1 else None
cur2 = cur2.next if cur2 else None
return tail.next
Java
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;
}
}