题目:
给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字0之外,这两个数都不会以0开头。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
代码实现:
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*Linklist;
void Init(Linklist &L)
{
L = (Linklist)malloc(sizeof(LNode));
L->next = NULL;
}
void Insert(Linklist &L,int e)
{
Linklist head = L;
Linklist p;
p = (Linklist)malloc(sizeof(LNode));
p->next = NULL;
while(head->next!=NULL)
{
head = head->next;
}
p->data = e;
head->next = p;
head = p;
}
void Dispose()
{
int n;
int count1;
int count2;
int a = 0,b = 0,c = 0;
Linklist A;
Linklist B;
Linklist C;
Init(A);
Init(B);
Init(C);
printf("请输入要存放第一个表的元素:");
while(1)
{
scanf("%d",&n);
if(n==-1)
{
break;
}
else
{
count1++;
Insert(A,n);
}
}
printf("请输入要存放第二个表的元素:");
while(1)
{
scanf("%d",&n);
if(n==-1)
{
break;
}
else
{
count2++;
Insert(B,n);
}
}
Linklist p = A;
Linklist q = B;
Linklist k = C;
a = p->next->data;
p = p->next;
count1--;
int i = 1;
while(p->next!=NULL)
{
if(count1>1)
{
i *= 10;
a += i*p->next->data;
}
p = p->next;
}
b = q->next->data;
q = q->next;
count2--;
i = 1;
while(q->next!=NULL)
{
if(count2>1)
{
i *= 10;
b += i*q->next->data;
}
q = q->next;
}
printf("a = %d ",a);
printf("b = %d ",b);
c = a+b;
printf("c = %d\n",c);
int t = 0;
while(c>0)
{
t = c%10;
c /= 10;
Insert(C,t);
}
while(k->next!=NULL)
{
k = k->next;
printf("%d->",k->data);
}
}
int main() {
Dispose();
return 0;
}