用链表实现大数据(超出int型的范围-2147483647—2147483647)的加法:
程序思想:
1、头插法创建两个字符串链表list1和list2,并把list1和list2的每个节点减去'0',即可得到数字;
2、先令进位flag等于0,如果接下来两个节点和进位相加的结果大于9,则取它们之和的余,用头插法输出,同时令进位flag为1;
3、如果两个节点和进位相加的结果小余9,则把它们之和用头插法输出;
4、以此类推,直到其中一个链表执行到尾,则把这个链表后面的值置为0,和另一个链表相加;
5、当两个链表执行到尾,结束循环,输出的结果即为输入的字符串之和。
#include<stdio.h>
#include<stdlib.h>
typedef char ElementType;
typedef struct node
{
ElementType data;
struct node *next;
}Node;
Node * createlist(void)
{
Node *head = NULL;
Node *p = NULL;
ElementType x;
while(1)
{
scanf("%c",&x);
if(x == '\n')
break;
p = (Node *)malloc(sizeof(*p));
p->data = x;
p->next = head;
head = p;
}
return head;
}
Node *sum(Node *list1,Node *list2)
{
int a,b,flag = 0,m;
Node *head = NULL;
Node *q = NULL;
while(list1||list2)
{
a = 0,b = 0;
if(list1)
{
a = (list1->data)-'0';
list1 = list1->next;
}
if(list2)
{
b = (list2->data)-'0';
list2 = list2->next;
}
if((a + b + flag) > 9)
{
m = (a+b+flag)%10;
flag = 1;
}
else
{
m = (a+b+flag);
flag = 0;
}
q = (Node *)malloc(sizeof(Node));
q->data = m;
q->next = head;
head = q;
}
if(flag)
{
q = (Node *)malloc(sizeof(Node));
q->data=1;
q->next=head;
head=q;
}
return head;
}
void Printlist(Node *s1)
{
printf("sum = ");
while(s1 != NULL)
{
printf("%d",s1->data);
s1 = s1->next;
}
printf("\n");
}
int main(int argc,char *argv[])
{
Node *list1 = createlist();
Node *list2 = createlist();
Node *s = sum(list1,list2);
Printlist(s);
return 0;
}