算法
时间复杂度:(O(n))
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = nullptr;
ListNode* cur = nullptr;
int carry = 0;
while (l1 != nullptr || l2 != nullptr || carry != 0) {
carry += (l1 == nullptr ? 0 : l1->val) + (l2 == nullptr ? 0 : l2->val);
auto tmp = new ListNode(carry % 10);
carry /= 10;
if (ans == nullptr) {
ans = tmp;
cur = ans;
} else {
cur->next = tmp;
cur = cur->next;
}
l1 = l1 == nullptr ? 0: l1->next;
l2 = l2 == nullptr ? 0: l2->next;
}
return ans;
}
};