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
[Solution]
说明:版权所有,转载请注明出处。 Coder007的博客/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// ignore null lists
if(l1 == NULL && l2 == NULL) return NULL;
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
// add
int carry = 0;
ListNode* p = NULL;
ListNode* head = NULL;
while(l1 != NULL || l2 != NULL){
// add
int sum = carry;
if(l1 != NULL){
sum += l1->val;
l1 = l1->next;
}
if(l2 != NULL){
sum += l2->val;
l2 = l2->next;
}
// update carry and sum
carry = sum / 10;
sum = sum % 10;
if(p == NULL){
p = new ListNode(sum);
head = p;
}
else{
ListNode *node = new ListNode(sum);
p->next = node;
p = p->next;
}
}
// be careful the last carry
if(carry > 0){
ListNode *node = new ListNode(carry);
p->next = node;
}
return head;
}
};