题目描述:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
解题思路:遍历链表,简单数学,用一个数来暂存得到的值的各位,一个来暂存进位
/**
* 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) {
if (!l1 || !l2)
return nullptr;
ListNode* resList = new ListNode(0);
ListNode* Now = resList;
int carry = 0;
int sum = 0;
ListNode* l = l1;
ListNode* r = l2;
while (l != nullptr && r != nullptr) {
sum = (l->val + r->val + carry) % 10;
carry = (l->val + r->val + carry) / 10;
ListNode* temp = new ListNode(sum);
Now->next = temp;
Now = temp;
l = l->next;
r = r->next;
}
while (l != nullptr) {
sum = (l->val + carry) % 10;
carry = (l->val + carry) / 10;
ListNode* temp = new ListNode(sum);
Now->next = temp;
Now = temp;
l = l->next;
}
while (r != nullptr) {
sum = (r->val + carry) % 10;
carry = (r->val + carry) / 10;
ListNode* temp = new ListNode(sum);
Now->next = temp;
Now = temp;
r = r->next;
}
if (carry == 0) {
Now -> next = nullptr;
} else {
Now->next = new ListNode(carry);
}
return resList->next;
}
};