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.
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* root = new ListNode(0);
ListNode* forward = root;
int carry=0, sum;
forward = root;
while(l1!=NULL || l2!=NULL)
{
sum=carry;
if(l1!=NULL)
{
sum += l1->val;
l1=l1->next;
}
if(l2!=NULL)
{
sum += l2->val;
l2=l2->next;
}
forward->next = new ListNode(sum%10);
carry = sum/10;
forward=forward->next;
}
if(carry)
forward->next = new ListNode(carry);
return root->next;
}
};
No comments:
Post a Comment