![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/be8978840361d3abad631ffa32c6cf57.png)
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode head(0), *p = &head;
int jinwei=0,number;
while(jinwei||l1||l2){
if(l1!=NULL&&l2!=NULL){
number = (l1->val + l2->val + jinwei)%10;
jinwei = (l1->val + l2->val + jinwei)/10 ;
}
if(l1==NULL&&l2!=NULL){
number = (l2->val + jinwei)%10;
jinwei = (l2->val + jinwei)/10 ;
}
if(l2==NULL&&l1!=NULL){
number = (l1->val + jinwei)%10;
jinwei = (l1->val + jinwei)/10 ;
}
p->next = new ListNode(number);
p = p->next;
if(l1!=NULL) l1 = l1->next;
if(l2!=NULL) l2 = l2->next;
}
return head.next;
}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode head(0), *p = &head;
int carry = 0;
while(l1 || l2 || carry){
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return head.next;
}
};