题目链接
Python3
方法: 模拟
⟮
O
(
n
)
、
O
(
1
)
⟯
\lgroup O(n)、O(1)\rgroup
⟮O(n)、O(1)⟯
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
cur = dummy = ListNode(None)
carry = 0
while l1 or l2:
carry += (l1.val if l1 else 0) + (l2.val if l2 else 0 )
cur.next = ListNode(carry % 10)
carry = carry // 10
cur = cur.next
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry > 0:
cur.next = ListNode(carry)
return dummy.next
C++
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(0);
ListNode* cur = dummy;
int carry = 0;
while (l1 || l2){
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int total = n1 + n2 + carry;
cur->next = new ListNode(total % 10);
carry = total / 10;
cur = cur->next;
if (l1){
l1 = l1->next;
}
if (l2){
l2 = l2->next;
}
}
if (carry > 0){
cur->next = new ListNode(carry);
}
return dummy->next;
}
};