#include
#include
struct ListNode{
int val;
struct ListNode *next;
};
struct ListNode * createList(int a[],int length)
{
printf("create list
");
int i;
struct ListNode *L=NULL;
struct ListNode *r=L;
for(i=0;ival=a[i];
s->next=NULL;
if(r!=NULL)
r->next=s;
else
L=s;
r=s;
}
return L;
}
struct ListNode * reverseList(struct ListNode *L)
{
printf("reverse list
");
struct ListNode *pre=NULL;
struct ListNode *p=L;
struct ListNode *q=L->next;
while(q!=NULL)
{
p->next=pre;
pre=p;
p=q;
q=q->next;
}
p->next=pre;
return p;
}
struct ListNode * addTowList(struct ListNode *L1,struct ListNode *L2)
{
struct ListNode *p1,*p2,*L;
p1=L1=reverseList(L1);
//displayList(L1);
p2=L2=reverseList(L2);
//displayList(L2);
int tmp=0;
while(p1!=NULL&&p2!=NULL)
{
int sum=p1->val+p2->val+tmp;
if(sum>=20)
{
tmp=2;
sum=sum-20;
}
else if(sum>=10)
{
tmp=1;
sum=sum-10;
}
else
tmp=0;
p1->val=p2->val=sum;
p1=p1->next;
p2=p2->next;
}
int flag=0;
if(p1!=NULL)
{
L=L1; //L1
while(p1!=NULL)
{
int sum=p1->val+tmp;
if(sum>=10)
{
tmp=1;
sum=sum-10;
}
else
{
tmp=0;
}
p1->val=sum;
p1=p1->next;
}
}
else if(p2!=NULL)
{
L=L2; //L2
while(p2!=NULL)
{
int sum=p2->val+tmp;
if(sum>=10)
{
tmp=1;
sum=sum-10;
}
else
{
tmp=0;
}
p2->val=sum;
p2=p2->next;
}
}
else
{
L=L1;
}
if(tmp!=0)
{
struct ListNode *s=(struct ListNode *)malloc(sizeof(struct ListNode));
s->val=tmp;
s->next=reverseList(L);
return s;
}
else
return reverseList(L);
}
void displayList(struct ListNode *L)
{
printf("print list:
");
struct ListNode *p=L;
while(p!=NULL)
{
printf("%d ",p->val);
p=p->next;
}
printf("
");
}
void distroyList(struct ListNode *L)
{
struct ListNode *pre=L;
struct ListNode *p=L->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=p->next;
}
free(pre);
}
int main()
{
//int a[3]={1,2,3};
//int b[4]={4,5,6,7,8};
int a[3]={9,9,9};
int b[5]={1,1,1,1,1};
struct ListNode *L1=createList(a,3);
displayList(L1);
struct ListNode *L2=createList(b,5);
displayList(L2);
struct ListNode *L=addTowList(L1,L2);
displayList(L);
distroyList(L);
return 0;
}
PS: ,