struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* l = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* p = l1,* q = l2, * t = l;
t->val = 0;
t->next = NULL;
while(p != NULL&&q != NULL)
{
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = 0;
node->next = NULL;
t->next = node;
t->val += (p->val + q->val);
if(t->val >= 10)
{
t->val -= 10;
node->val = 1;
}
p = p->next;
q = q->next;
if(p == NULL&&q == NULL&&t->next->val == 0) //防止最后出现一个0
t->next = NULL;
t = t->next;
}
while(p != NULL) //l1未结束而l2结束了
{
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = 0;
node->next = NULL;
t->next = node;
t->val += p->val;
if(t->val >= 10)
{
t->val -= 10;
node->val = 1;
}
p = p->next;
if(p == NULL&&t->next->val == 0)
t->next = NULL;
t = t->next;
}
while(q != NULL) //l2未结束而l1结束了
{
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = 0;
node->next = NULL;
t->next = node;
t->val += q->val;
if(t->val >= 10)
{
t->val -= 10;
node->val = 1;
}
q = q->next;
if(q == NULL&&t->next->val == 0)
t->next = NULL;
t = t->next;
}
return l;
}