目录
题目:
代码:
#include <stdio.h>
#include <stdlib.h>
struct List
{
int val;
struct List* next;
};
void printfList(struct List* head)
{
while(head){
printf("%d",head->val);
head = head->next;
}
putchar('\n');
}
int ListLen(struct List* head)
{
int len = 0;
while(head){
len++;
head = head->next;
}
return len;
}
void makeList(struct List* head,int num)
{
num = num-1;
if(num == 0){
return;
}
int i = 2;
struct List* new = NULL;
while(num>0){
new = (struct List*)malloc(sizeof(struct List));
head->next = new;
new->val = i;
new->next = NULL;
head = new;
i++;
num--;
}
}
void inNewList(struct List* head)
{
struct List* new = NULL;
new = (struct List*)malloc(sizeof(struct List));
new->val = 1;
new->next = NULL;
while(head){
if(head->next == NULL){
head->next = new;
head = new;
}
head = head->next;
}
}
int shixian(struct List* head,struct List* l1,struct List* l2)
{
int flag = 0;
while(head){
if(l1&&l2){
head->val = flag + l1->val + l2->val;
if(head->val >= 10){
flag = 1;
head->val = head->val%10;
}else{
flag = 0;
head->val = head->val;
}
head = head->next;
l1 = l1->next;
l2 = l2->next;
}
if(l1!=NULL&&l2==NULL){
head->val = flag + l1->val;
if(head->val >= 10){
flag = 1;
head->val = head->val%10;
}else{
flag = 0;
head->val = head->val;
}
head = head->next;
l1 = l1->next;
}
if(l1==NULL&&l2!=NULL){
head->val = flag + l2->val;
if(head->val >= 10){
flag = 1;
head->val = head->val%10;
}else{
flag = 0;
head->val = head->val;
}
head = head->next;
l2 = l2->next;
}
}
return flag;
}
struct List* add(struct List* l1, struct List* l2)
{
struct List* pro = NULL;
struct List* new = NULL;
int len1 = 0;
int len2 = 0;
int pro_Len = 0;
int flag = 0;
len1 = ListLen(l1);
len2 = ListLen(l2);
pro = (struct List*)malloc(sizeof(struct List));
pro->val = 0;
pro->next = NULL;
pro_Len = len1>=len2?len1:len2;
makeList(pro,pro_Len);
flag = shixian(pro,l1,l2);
if(flag == 1){
inNewList(pro);
}
return pro;
}
int main()
{
struct List* L1;
struct List* L2;
struct List* sum;
L1 = (struct List*)malloc(sizeof(struct List));
L2 = (struct List*)malloc(sizeof(struct List));
sum = (struct List*)malloc(sizeof(struct List));
makeList(L1,3);
makeList(L2,2);
L1->val = 2;
L1->next->val = 4;
L1->next->next->val = 3;
L2->val = 5;
L2->next->val = 6;
//L2->next->next->val = 4;
/*printf("L1:%d\n",L1->val);
printf("L1-next:%d\n",L1->next->val);
printf("L2:%d\n",L2->val);*/
sum = add(L1,L2);
printf("input L1:");
printfList(L1);
printf("input L2:");
printfList(L2);
printf("output sum:");
printfList(sum);
return 0;
}