2022/3/3更新:修复了结果缺失一位的bug。不过很离谱啊,唯一修改的地方就是把printf移动了个位置,见main()中注释。
没有使用free()函数
大数的运算用数组做更方便,只是根据题目要求使用循环链表来做。
//超长正整数的加法。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define numLength 100 //输入最大数长
typedef struct node{ //循环链表
int num;
int length;
struct node *pre;
struct node *next;
}Node;
void addNode(Node *pNode, int num);
void printNode(Node pNode, int direction);
void numPlus(Node pNode1, Node pNode2);
int main(){
char tmp[numLength], tmp2[numLength];
int tmp3;
Node pHead, pHead2;
while(1){
pHead.next = pHead.pre = &pHead;
pHead2.next = pHead2.pre = &pHead2;
printf("输入第一个数:"); gets(tmp);
printf("输入第二个数:"); gets(tmp2);
while(strlen(tmp)){
tmp3=tmp[strlen(tmp)-1]-'0';
tmp[strlen(tmp)-1]='\0';
addNode(&pHead, tmp3);
}
while(strlen(tmp2)){
tmp3=tmp2[strlen(tmp2)-1]-'0';
tmp2[strlen(tmp2)-1]='\0';
addNode(&pHead2, tmp3);
}
// printf("\n pHead长度:%d", pHead.length);
// printf("\n pHead2长度:%d", pHead2.length);
printf("链表相加结果:");//离谱!这里随便print个东西,就能正常输出了,一注释这行就没用了,以前不用注释也行,难道C版本更新了?
//本来上面的print是在numPlus函数里的,但是这里不print一下,结尾会少输出一个值。
numPlus(pHead, pHead2);
pHead.length=0;
pHead2.length=0;
}
return 0;
}
void addNode(Node *pNode, int num){//头插法
Node *pNew;
if((pNew = (Node*)malloc(sizeof(Node))) == NULL){
printf("创建新结点错误");
exit(0);
}
pNew->next = pNode->next;//将新结点的后继变成前一个的后继
pNew->pre = pNode;//将新结点的前驱变成前一个
pNode->next->pre = pNew;//将前一个的后继的前驱变成新结点
pNode->next = pNew;//将前一个的后继变成新结点
pNew->num = num;
pNode->length+=1;
}
void printNode(Node pNode, int direction){//direction非零逆向输出
Node *pNew;
pNew = &pNode;
int i=0;
if(direction){
while(i++<pNode.length){
// printf("\n%d, %d \n", i, pNode.length);
pNew= pNew->pre;
printf("%d", pNew->num);
}
}
else{
while(i++<pNode.length){
// printf("\n%d, %d \n", i, pNode.length);
pNew= pNew->next;
printf("%d", pNew->num);
}
}
printf("\n");
}
void numPlus(Node pNode1, Node pNode2){
Node pNode3;
Node *tmp1=&pNode1, *tmp2=&pNode2;
int i=0, carry=0, sum=0, pd =0;
pNode3.next = pNode3.pre = &pNode3;
while(i<pNode1.length || i<pNode2.length){
i++; tmp1=tmp1->pre; tmp2=tmp2->pre;
if (i>pNode1.length) tmp1->num = 0;
if (i>pNode2.length) tmp2->num = 0;
sum = tmp1->num + tmp2->num + carry;
if(sum>9){
sum%=10;
carry=1;
if((i>=pNode1.length && i>=pNode2.length && carry ==1))pd=1;
}
else carry = 0;
addNode(&pNode3, sum);
}
if(pd) addNode(&pNode3,1);
// printf("\n pNode1长度:%d", pNode1.length);
// printf("\n pNode2长度:%d", pNode2.length);
printNode(pNode3, 0);
}
结果: