题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
int i1=0,i=0,j1=0,j=0;
struct ListNode* p1=head1,*p2=head1,*p3=head2;
int a[1000000],b[1000000];//用来记录两个链表节点值
while(head1){
a[i1++]=head1->val;
head1=head1->next;
}
while(head2){
b[j1++]=head2->val;
head2=head2->next;
}
i=i1;j=j1;
printf("%d %d",i1,j1);
int num[i1+j1];int length=0,c=0;
for(;i1&&j1;i1--,j1--){//同位相加,c表示进位,结束条件:a数组或b数组任一值取完。
num[length++]=(a[i1-1]+b[j1-1]+c)%10;
c=(a[i1-1]+b[j1-1]+c)/10;
}
//对于没取完值的数组,继续存到num数组中
while(i1!=0){
num[length++]=(a[i1-1]+c)%10;
c=(a[i1-1]+c)/10;
i1--;
}
while(j1!=0){
num[length++]=(b[j1-1]+c)%10;
c=(b[j1-1]+c)/10;
j1--;
}
//最后一位如果进位大于0,则再存入
if(c)
num[length++]=c;
//从链表一开始依次存入num数组值,当链表一指针即将指向空时,将其连接到链表二。
while(length){
p1->val=num[--length];
i--;
if(!i){//链表一指针指向空
p1->next=p3;
}
if(!length){//当最后一个num数组值存入时,节点指针指向空
p1->next=NULL;
return p2;//返回首节点
}
p1=p1->next;
}
return p2;
}
查看17道真题和解析
