/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2)
{
vector<int> a;
vector <int> b;
ListNode*p=head1;
ListNode*q=head2;
while(p)
{
a.push_back(p->val);
p=p->next;
}
while(q)
{
b.push_back(q->val);
q=q->next;
}
int len1=a.size();
int len2=b.size();
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
int i=0;
int c=0;
vector <int> ans;
if(len1>=len2)
{
for(i=0;i<len2;i++)
{
int m=a[i]+b[i]+c;
ans.push_back(m%10);
if(m>=10)
{
c=1;
}
else
{
c=0;
}
}
for(i=len2;i<len1;i++)
{
int m=a[i]+c;
ans.push_back(m%10);
if(m>=10)
{
c=1;
}
else
{
c=0;
}
}
if(c)
{
ans.push_back(c);
}
}
else
{
for(i=0;i<len1;i++)
{
int m=a[i]+b[i]+c;
ans.push_back(m%10);
if(m>=10)
{
c=1;
}
else
{
c=0;
}
}
for(i=len1;i<len2;i++)
{
int m=b[i]+c;
ans.push_back(m%10);
if(m>=10)
{
c=1;
}
else
{
c=0;
}
}
if(c)
{
ans.push_back(c);
}
}
ListNode*ans2=NULL;
ListNode*t=NULL;
int len3=ans.size();
if(len3>0)
{
ans2=t=new ListNode(ans[len3-1]);
}
for(i=len3-2;i>=0;i--)
{
t->next=new ListNode(ans[i]);
t=t->next;
}
return ans2;
}
};



京公网安备 11010502036488号