for save space, I write a really ugly code here.
/**
* 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) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode * head1 = l1;
int carry = 0;
while(l1->next!= NULL && l2->next!= NULL)
{
int temp = l1->val + l2->val + carry;
carry = temp/10;
l1->val = temp%10;
l1 = l1->next;
l2 = l2->next;
}
while(1)
{
if(l1->next != NULL && l2->next == NULL)
{
int temp = l1->val + l2->val +carry;
carry = temp/10;
l1->val = temp%10;
l1 = l1->next;
break;
}
if(l1->next == NULL&& l2->next!= NULL)
{
int temp = l1->val + l2->val +carry;
carry = temp/10;
l1->val = temp%10;
l1->next = l2->next;
l1 = l1->next;
break;
}
if(l1->next == NULL && l2->next == NULL)
{
l1->val = l1->val + l2->val;
break;
}
}
while(l1->next!= NULL)
{
int temp = l1->val + carry;
carry = temp/10;
l1->val = temp%10;
l1 = l1->next;
}
int temp = l1->val + carry;
l1->val = temp%10;
carry = temp/10;
if(carry)
{
ListNode *l3 = new ListNode(1);
l1->next = l3;
}
return head1;
}
};