给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
#include<stdio.h>
typedef struct num * p;
struct num
{
/* data */
int number;
struct num * next;
};
typedef p list;
list makelist(void);
void print(list p);
list list_sum(list p,list pro);
int main(){
list one,two,result;
one = makelist();
two = makelist();
result = list_sum(one,two);
print(result);
return 0;
}
list makelist(void){
list P,head= NULL ;
int n=0;
P = (list)malloc(sizeof(list));
scanf("%d",&P->number);
P->next = head; //将p的下一个设为0
head= P; //将
P = head->next;
while(getchar() != '\n'){
P = (list)malloc(sizeof(list));
scanf("%d",&P->number);
P->next = head; //将p的下一个设为0
head= P; //将
P = head->next;
}
return head;
}
void print(list p){
while(p!= NULL){
printf("%d ",p->number);
p = p->next;
}
printf("\n");
}
list list_sum(list p,list pro){
list result,head,prolist;
// head =NULL;
int n = 0;
prolist = result = (list)malloc(sizeof(list));
while(p!= NULL){
result->number = p->number + pro->number;
if (n == 0){
head = result;
}
else{
prolist->next = result;
}
prolist = result; //当n=0继承result的地址,第二次是就相当于result->next = result
n++;
p = p->next;
pro = pro->next;
result = (list)malloc(sizeof(list));
}
prolist->next= NULL;
return head;
}