题解 | #链表相加(二)# C头插法反转链表后相加值赋予头插法创建新链表
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
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;
}