struct ListNode* addTwoNumbers(struct ListNode* head1, struct ListNode* head2){
struct ListNode* H1=malloc(sizeof(struct ListNode));
struct ListNode* H2=malloc(sizeof(struct ListNode));
struct ListNode* p,*q;
H1->next=NULL;
H2->next=NULL;
//头插法两个链表反转
while(head1!=NULL&&head2!=NULL)
{
p=head1;
q=head2;
head1=head1->next;
head2=head2->next;
p->next=H1->next;
H1->next=p;
q->next=H2->next;
H2->next=q;
}
//长度不同的特殊处理
while(head1!=NULL)
{
p=head1;
head1=head1->next;
p->next=H1->next;
H1->next=p;
}
while(head2!=NULL)
{
q=head2;
head2=head2->next;
q->next=H2->next;
H2->next=q;
}
head1=H1->next;
head2=H2->next;
int sum;
int add=0;
H1->next=NULL;
//值相加,头插法创建新链表
while(head1!=NULL||head2!=NULL)
{
struct ListNode* temp=malloc(sizeof(struct ListNode));
int a=0,b=0;
if(head1!=NULL)
a=head1->val;
else
a=0;
if(head2!=NULL)
b=head2->val;
else
b=0;
sum=(a+b+add);
add=sum/10;
sum=sum%10;
temp->val=sum;
temp->next=H1->next;
H1->next=temp;
if(head1!=NULL)
head1=head1->next;
if(head2!=NULL)
head2=head2->next;
}
//最终若有进位值特殊处理
if(add==1)
{
p=H1;
struct ListNode* temp=malloc(sizeof(struct ListNode));
temp->val=1;
temp->next=H1->next;
H1->next=temp;
}
return H1->next;
}
04-04
278
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)