实现任意范围的两个整数的加法( 整数的范围用 int 型的变量无法表示)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
int score;
struct node *next;
}*link, Node;
void plusSuper(){
char *a = (char*)malloc(50);
char *b = (char*)malloc(50);
char ch, ah;
int sum = 0, flag;
Node *p, *head, *head1, *newhead;
head = head1 = newhead = NULL;
while(gets(a)!=NULL && gets(b)!=NULL){
while(*a != '\0'){
p = (Node*)malloc(sizeof(Node));
p->score = *a - 48;
p->next = NULL;
if(head == NULL){
head = p;
}
else{
p->next = head;
head = p;
}
a++;
}
while(*b != '\0'){
p = (Node*)malloc(sizeof(Node));
p->score = *b - 48;
p->next = NULL;
if(head1 == NULL){
head1 = p;
}
else{
p->next = head1;
head1 = p;
}
b++;
}
//plus
flag = 0;//进位标志
while(head!=NULL && head1!=NULL){
sum = head->score + head1->score + flag;
if(newhead == NULL){
newhead = head;
head = head->next;
newhead->next = NULL;
if(sum > 9){
newhead->score = sum - 10;
flag = 1;
}
else{
newhead->score = sum;
}
}
else{
p = head->next;
head->next = newhead;
newhead = head;
head = p;
if(sum < 10){
newhead->score = sum;
flag = 0;
}
else{
newhead->score = sum - 10;
flag = 1;
}
}
p = head1;
head1 = head1->next;
free(p);
}
if(head == NULL && head1 == NULL){
if(flag == 1){
p = (Node*)malloc(sizeof(Node));
p->score = 1;
p->next = newhead;
newhead = p;
}
}
if(head == NULL){
head = head1;
}
while(head != NULL){
sum = head->score + flag;
p = head->next;
head->next = newhead;
newhead = head;
head = p;
if(sum > 9){
newhead->score = sum - 10;
flag = 1;
}
else{
newhead->score = sum;
flag = 0;
}
}
//flag 的处理
if(flag == 1){
p = (Node*)malloc(sizeof(Node));
p->score = 1;
p->next = newhead;
newhead = p;
}
//The output of result
while(newhead != NULL){
printf("%d", newhead->score);
newhead = newhead->next;
}
printf("\n");
head = head1 = newhead = NULL;
}
}