LeetCode OJ ProblemAdd: Two Numbers
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) {
if(l1 == NULL)
return l2;
else if(l2 == NULL)
return l1;
int flag = 0; //记录进位
ListNode *p, *pre_p, *r;
pre_p = p = l1;
r = l2;
while(p && r)
{
if(flag)
p->val += r->val + 1;
else
p->val += r->val;
if(p->val >= 10)
{
p->val -= 10;
flag = 1;
}
else
flag = 0;
pre_p = p;
p = p->next;
r = r->next;
}
if(!r && !p)
{
if(flag)
pre_p->next = new ListNode(1);
}
else
{
if(!p)
{
pre_p->next = r;
p = r;
}
if(flag)
{
while(p && flag)
{
p->val += 1;
if(p->val >= 10)
{
p->val -= 10;
flag = 1;
}
else
flag = 0;
pre_p = p;
p = p->next;
}
if(!p && flag)
pre_p->next = new ListNode(1);
}
}
return l1;
}
};