/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==nullptr) return l2;
if(l2==nullptr) return l1;
ListNode*phead = new ListNode(-1);
ListNode*prev = phead;
int carry = 0;
int temp = 0;
int remaid=0;
while(l1!=nullptr||l2!=nullptr)
{
if(l1!=nullptr&&l2==nullptr)
{
temp = l1->val+carry;
carry=0;
l1 = l1->next;
}
else if(l2!=nullptr&&l1==nullptr)
{
temp = l2->val+carry;
carry=0;
l2 = l2->next;
}
else{
temp = l1->val+l2->val+carry;
carry=0;
l1 = l1->next;
l2 = l2->next;
}
if(temp>=10)
{
remaid = temp%10;
ListNode*p_new = new ListNode(remaid);
prev->next = p_new;
prev = p_new;
carry ++;
}
else{
ListNode*p_new = new ListNode(temp);
prev->next = p_new;
prev = p_new;
}
}
if(carry==1)
{
ListNode*p_new = new ListNode(carry);
prev->next = p_new;
}
return phead->next;
}
};