用链表对两个大数进行相加
输入的第一个数字是数的位数
例子:
创建结点
struct node
{//链表结点类型,包含一个存放整型数据的 data 成员,和一个指向下一个结点的next成员
int data ;
struct node *next ;
};
创建空链表
struct node *mycreateList()
{//函数功能:创建一个只有一个头结点的空链表,头节点的数据域赋值为0,并将表头结点的地址返回
struct node *head = (struct node *)malloc(sizeof(struct node));
head->data = 0;
head->next = NULL;
return head;
}
链表头插法
void myinsertHead(struct node * head, int insData )
{
/*函数功能:实现在head为表头的链表中使用头插法,插入数据元素insData*/
struct node *p ;
p = (struct node *)malloc(sizeof(struct node));
p->data = insData;
p->next = head->next ;
head->next = p ;
}
链表尾插法
void myinsertTail(struct node * head , int insData )
{
/*在head为表头的单链表表尾插入数据元素insData*/
struct node *p ,*q ;
p = (struct node *)malloc(sizeof(struct node));
p->data = insData;
p->next = NULL;
q = head ;
while(q->next!=NULL)
{
q = q->next;
}
q->next = p ;
}
输出大数相加的结果
void myprintList(struct node *L)
{
/*输出head为表头的链表中的数据元素*/
struct node *p = L->next ;
while(p)
{
printf("%d ",p->data);
p = p->next ;
}
}
接收大数的各个位
将大数的各个位用头插法插入链表,因为在进行大数相加的时候,我们是从低位往高位进行相加,方便后面对两个大数进行相加。
void genNumber( struct node *A , int num)
{//接收输入的大数的各个位
int i;
int data;
printf("请输入大数的各个位(用空格隔开)\n");
for(i=0;i<num;i++)//使用头插法
{
scanf("%d",&data);
myinsertHead(A,data);
}
return;
}
两个大数相加
struct node *addNumber(struct node *A ,struct node *B)
{
//求两数相加之和
struct node *p1,*p2,*p,*head;
p1=A->next;
p2=B->next;
p=mycreateList();
head=p;
int sum=0,count=0;//count表示各个位相加是否有进位
while(p1!=NULL||p2!=NULL)//使用头插法
{
if(p1!=NULL&&p2!=NULL)
{
sum=p1->data+p2->data;
if(count==0)
{
if(sum>=10)
{
sum=sum%10;
count=1;
}
else
{
count=0;
}
myinsertHead(p,sum);
}
else
{
sum=sum+1;
if(sum>=10)
{
sum=sum%10;
count=1;
}
else
{
count=0;
}
myinsertHead(p,sum);
}
p1=p1->next;
p2=p2->next;
}
if(p1==NULL&&p2!=NULL)//p1代表的数比较小
{
sum=p2->data;
if(count==0)
{
myinsertHead(p,sum);
}
else
{
sum=sum+1;
if(sum>=10)
{
sum=sum%10;
count=1;
}
else
{
count=0;
}
myinsertHead(p,sum);
}
p2=p2->next;
}
if(p1!=NULL&&p2==NULL)//p2代表的值比较小
{
sum=p1->data;
if(count==0)
{
myinsertHead(p,sum);
}
else
{
sum=sum+1;
if(sum>=10)
{
sum=sum%10;
count=1;
}
else
{
count=0;
}
myinsertHead(p,sum);
}
p1=p1->next;
}
}
if(count==1)
{
myinsertHead(p,1);
}
return head;
}
主函数
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct node *A ,*B ,*C ;
int i,j;
A = mycreateList();
B = mycreateList();
printf("请输入第一个数的位数:\n");
scanf("%d",&i);
genNumber(A,i);
printf("请输入第二个数的位数:\n");
scanf("%d",&j);
genNumber(B,j) ;
C = addNumber(A,B);
printf("两数相加后的结果:\n");
myprintList(C);
return 0;
}