题目要求如下:
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) {
ListNode* retVal = new ListNode(0);
ListNode* head = retVal;
int carry = 0;
while (l1 != NULL || l2 != NULL) {
int val1 = 0;
int val2 = 0;
if (l1 != NULL)
val1 = l1->val;
if (l2 != NULL)
val2 = l2->val;
int sum = val1 + val2 + carry;
if (sum >= 10) {
sum -= 10;
carry = 1;
}
else
carry = 0;
ListNode* cur = new ListNode(sum);
head->next = cur;
head = head->next;
if (l1 != NULL)
l1 = l1->next;
if (l2 != NULL)
l2 = l2->next;
}
if (carry != 0) {
ListNode* cur = new ListNode(1);
head->next = cur;
head = head->next;
}
return retVal->next;
}
};