题目:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:按节点相加。
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int carry = 0;
ListNode dummy(0);
ListNode* runner = &dummy;
while (l1 != nullptr || l2 != nullptr || carry != 0) {
int num1 = (l1 == nullptr) ? 0 : l1->val;
int num2 = (l2 == nullptr) ? 0 : l2->val;
int sum = num1 + num2 + carry;
carry = sum / 10;
ListNode* new_digit = new ListNode(sum % 10);
runner->next = new_digit;
runner = new_digit;
l1 = l1 == nullptr ? nullptr : l1->next;
l2 = l2 == nullptr ? nullptr : l2->next;
}
return dummy.next;
}
};
总结:复杂度O(n + m).