c语言链表实现超大十进制数的加法,但是输出不出结果,请问有什么问题?
#include<stdio.h>
#include<malloc.h>
typedef struct PolyArray
{
int coef;
int exp;
}PolyArray;
typedef struct PolyNode
{
PolyArray data;
struct PolyNode* next;
}PolyNode;
void IntArray(PolyArray** array)
{
FILE* fp;
char str[] = "D:\\visualstudio\\数据结构作业\\input.txt";
fopen_s(&fp, str, "rt");
if (!fp)
{
printf("open file error");
}
int* i = NULL;
i[0] = 0, i[1] = 0;
char c = '\0';
if (fp)
{
while(array)
{
while (c = fgetc(fp))
{
(*array)[*i].coef = c - '0';
(*array)[*i].exp = *i;
(*i)++;
if (c == '\n')
{
array++;
i++;
}
}
}
fclose(fp);
}
}
void CreatePoly(PolyNode** head, int m, PolyArray* array)
{
PolyNode* prev = NULL;
*head = (PolyNode*)malloc(sizeof(PolyNode));
if ((*head))
(*head)->next = NULL;
for (int i = 0; i < m; i++)
{
PolyNode* p = (PolyNode*)malloc(sizeof(PolyNode));
if (p)
{
p->data.coef = array[i].coef;
p->data.exp = array[i].exp;
p->next = NULL;
if (!prev)
{
prev = *head;
}
prev->next = p;
prev = p;
}
}
}
int ComparePoly(PolyNode* a, PolyNode* b)
{
if (a->data.exp < b->data.exp)
return 1;
else if (a->data.exp > b->data.exp)
return -1;
else return 0;
}
PolyNode* AddPoly(PolyNode* ha, PolyNode* hb, PolyNode* hc)
{
PolyNode* p, * q, * newp, * newh;
p = ha->next;
q = hb->next;
newh = hc;
while (p && q)
{
switch (ComparePoly(p, q))
{
case 1:
newh->next = p;
newh = p;
p = p->next;
break;
case -1:
newh->next = q;
newh = q;
q = q->next;
break;
case 0:
int sum = p->data.coef + q->data.coef;
int remain = sum % 10;
if (sum != 0.0)
{
newp = (PolyNode*)malloc(sizeof(PolyNode));
if (newp)
{
newp->data.coef = remain;
newp->data.exp = q->data.exp;
newp->next = NULL;
newh->next = newp;
newp->data.coef = newp->data.coef + (sum - (sum % 10)) / 10;
newh = newp;
}
}
p = p->next;
q = q->next;
break;
}
}
newh->next = p ? p : q;
return hc;
}
void ExchangePoly(PolyNode* head)
{
PolyNode* p, * q, * tmp;
p = (PolyNode*)malloc(sizeof(PolyNode));
q = (PolyNode*)malloc(sizeof(PolyNode));
tmp = (PolyNode*)malloc(sizeof(PolyNode));
p = head->next;
while (p)
{
q = p->next;
while (q)
{
if (q->data.exp > p->data.exp)
{
if (tmp)
{
tmp->data = p->data;
p->data = q->data;
q->data = tmp->data;
}
}
q = q->next;
}
p = p->next;
}
}
void PrintPoly(FILE* fp, PolyNode* head)
{
ExchangePoly(head);
PolyNode* s = head->next;
while (s)
{
printf("(%d %d)\n", s->data.coef, s->data.exp);
fprintf(fp, "(%d,%d)\n", s->data.coef, s->data.exp);
s = s->next;
}
}
int main()
{
FILE* fp;
char str[] = "D:\\visualstudio\\数据结构作业\\input.txt";
PolyNode* ha, * hb, * hc;
PolyArray** array = NULL;
if (array)
{
array[0] = (PolyArray*)malloc(sizeof(PolyArray) * 128);
array[1] = (PolyArray*)malloc(sizeof(PolyArray) * 128);
}
IntArray(array);
fopen_s(&fp, str, "at");
if (!fp)
{
printf("open file error");
return 0;
}
CreatePoly(&ha, 12, array[0]);
CreatePoly(&hb, 12, array[1]);
hc = (PolyNode*)malloc(sizeof(PolyNode));
AddPoly(ha, hb, hc);
PrintPoly(fp, hc);
free(ha);
free(hb);
free(hc);
free(array[0]);
free(array[1]);
fclose(fp);
return 0;
}