/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* reversList(ListNode* head)
{
if(!head) return nullptr;
ListNode* pre=nullptr,*cur=head, *nex=nullptr;
while(cur)
{
nex=cur->next;
cur->next = pre;
pre = cur;
cur=nex;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
if(!head1 || !head2) return head1==nullptr ? head2 : head1;
head1 = reversList(head1);
head2 = reversList(head2);
ListNode* head = new ListNode(0);
int flag=0;
while(head1 && head2)
{
int temp = head1->val + head2->val + flag;
flag = temp>9 ? 1 : 0;
temp %= 10;
ListNode* cur = new ListNode(temp);
cur->next = head->next;
head->next = cur;
head1=head1->next;
head2 = head2->next;
}
while(head1)
{
int temp = head1->val + flag;
flag = temp>9 ? 1 : 0;
temp %= 10;
ListNode* cur = new ListNode(temp);
cur->next = head->next;
head->next = cur;
head1=head1->next;
}
while(head2)
{
int temp = head2->val + flag;
flag = temp>9 ? 1 : 0;
temp %= 10;
ListNode* cur = new ListNode(temp);
cur->next = head->next;
head->next = cur;
head2 = head2->next;
}
head->val = flag;
return head->val ? head : head->next;
}
};