题解:链表的遍历注意最后一位的进位,为此需要新建一个数据项
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int x=0,y=0;
ListNode* p=l1;
ListNode* q=l2;
int ra=0;
ListNode* head=(ListNode*)malloc(sizeof(ListNode));
ListNode* r=head;
while(p&&q){
int x=p->val+q->val;
x+=ra;
ListNode* t =(ListNode*)malloc(sizeof(ListNode));
t->val=x%10;
ra=x/10;
r->next=t;
r=t;
p=p->next;
q=q->next;
}
while(p)
{
int x=p->val;
x+=ra;
ListNode* t =(ListNode*)malloc(sizeof(ListNode));
t->val=x%10;
ra=x/10;
r->next=t;
r=t;
p=p->next;
}
while(q)
{
int x=q->val;
x+=ra;
ListNode* t =(ListNode*)malloc(sizeof(ListNode));
t->val=x%10;
ra=x/10;
r->next=t;
r=t;
q=q->next;
}
if(ra){
ListNode* t =(ListNode*)malloc(sizeof(ListNode));
t->val=ra;
r->next=t;
r=t;
}
r->next=NULL;
return head->next;
}
};