链表的输入问题
代码的功能就是完成一元多项式的加法运算,问题出现在读取链表时,读取一个链表时代码并没有出现问题,但是当读取两个链表时,第一个链表在释放头结点时出现错误:unknown signal,第二链表读取无误,两个链表读取完成之后第一个链表尾指针发生了改变,导致报错,现在想请教一下各位大神代码报错原因。代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct PolyNode *Polynomial;
struct PolyNode
{
int coef;
int expon;
Polynomial link;
};
int Compare(int e1,int e2)
{
if (e1 > e2)
{
return 1;
}
else if (e1 < e2)
{
return -1;
}
else
{
return 0;
}
}
void Attach(int c,int e,Polynomial *pRear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->coef = c;
P->expon = e;
(*pRear)->link = P;
*pRear = P;
}
Polynomial ReadPoly()
{
Polynomial Head,Rear,t;
int c,e,i,N;
scanf("%d",&N);
Head = (Polynomial)malloc(sizeof(struct PolyNode));
Head = Rear;
for ( i = 0; i < N; i++)
{
scanf("%d %d",&c,&e);
Attach(c,e,&Rear);
}
Rear->link = NULL;
t = Head;
Head = Head->link;
free(t);
t = NULL;
return Head;
}
void PrintPoly(Polynomial P)
{
int flag = 0;
while (P)
{
if (!flag)
{
flag = 1;
}
else
{
printf(" ");
}
printf("%d %d",P->coef,P->expon);
P = P->link;
}
printf("\n");
}
Polynomial PolyAdd(Polynomial P1,Polynomial P2)
{
Polynomial front,rear,temp;
int sum;
front = (Polynomial)malloc(sizeof(struct PolyNode));
rear = front;
while (P1 && P2)
{
switch (Compare(P1->expon,P2->expon))
{
case 1:
Attach(P1->coef,P1->expon,&rear);
P1 = P1->link;
break;
case -1:
Attach(P2->coef,P2->expon,&rear);
P2 = P2->link;
break;
case 0:
sum = P1->coef + P2->coef;
Attach(sum,P1->expon,&rear);
P1 = P1->link;
P2 = P2->link;
break;
}
}
while (P1)
{
Attach(P1->coef,P1->expon,&rear);
P1 = P1->link;
}
while (P2)
{
Attach(P2->coef,P2->expon,&rear);
P2 = P2->link;
}
rear->link = NULL;
temp = front;
front = front->link;
free(temp);
return front;
}
int main()
{
Polynomial P1,P2,PAdd,PMultiple;
P1 = ReadPoly();
P2 = ReadPoly();
PAdd = PolyAdd(P1,P2);
PrintPoly(PAdd);
return 0;
}