题目解释:
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* result = new ListNode(0);
ListNode* current = result;
bool check= true;
while( l1!=NULL && l2!=NULL ){
current->next = new ListNode(0);
current->next->val = l1->val + l2->val + carry;
if( current->next->val >=10 )
{
current->next->val = current->next->val - 10;
carry = 1;
}
else
carry = 0;
current = current->next;
l1 = l1->next;
l2 = l2->next;
}
while( l2!=NULL )
{
current->next = new ListNode(0);
current->next->val = l2->val + carry;
if( current->next->val >=10 )
{
current->next->val = current->next->val - 10;
carry = 1;
}
else
carry = 0;
current = current->next;
l2 = l2->next;
}
while( l1!=NULL )
{
current->next = new ListNode(0);
current->next->val = l1->val + carry;
if( current->next->val >=10 )
{
current->next->val = current->next->val - 10;
carry = 1;
}
else
carry = 0;
current = current->next;
l1 = l1->next;
}
if( carry == 1)
{
current->next = new ListNode(0);
current->next->val = carry;
}
return result->next;
}
};