多项式相加的问题
程序运行之后显示内存不能read。麻烦看下哪里出错了。#include<stdlib.h>
#include<stdio.h>
#include<ctype.h>
#include<malloc.h>
#include<iostream.h>
typedef struct pnode{
float coef;
int exp;
struct pnode *next;
struct pnode *prior;
}polynode;
polynode *add(polynode *pa,polynode *pb)
{
polynode *p,*q,*r,*s,*t;
float x;
p=pa->next;q=pb->next;
s=pa;
while((p!=pa)&&(q!=pb))
{
if(p->exp<q->exp){s=p;p=p->next;}
if(p->exp>q->exp){r=q->next;q->next=p;s->next=q;s=q;q=r;}
else{
x=p->coef+q->coef;
if(x!=0){p->coef=x;s=p;}
else{s->next=p->next;free(p);}
p=s->next;r=q;q=q->next;free(r);
}
}
if(q!=pb)
{t=q;
while(t->next!=pb)t=t->next;
s->next=q;
t->next=pa;
}
return(pa);
}
polynode * CreatPolyn(polynode *P,int m)
{
if(m <= 0) return NULL;
polynode *h = P = (pnode*)malloc(sizeof(pnode)), *Q;
P->coef = 0.0;
int i;
printf("输入%d个非零项\n",m);
for (i = 1; i <= m; ++i)
{
scanf("%f%d",&P->coef,&P->exp);
if(P->coef)
Q = P;
P = P->next = (polynode*)malloc(sizeof(polynode));
}
Q->next = NULL;
free(P);
return h;
} // CreatPolyn
void PrintfPoly(polynode *P)
{
polynode *q = P;
if(!q) {
putchar('0');
return;
}
if(q->coef!=1)
{
printf("%g",q->coef);
if(q->exp==1) putchar('X');
else if(q->exp) printf("X^%d",q->exp);
}
else if(!q->exp) putchar('1');
else if(q->exp==1) putchar('X');
else printf("X^%d",q->exp);
q = q->next;
while (q)
{
if(q->coef > 0) putchar('+');
if(q->coef!=1)
{
printf("%g",q->coef);
if(q->exp==1) putchar('X');
else if(q->exp) printf("X^%d",q->exp);
}
else if(!q->exp) putchar('1');
else if(q->exp==1) putchar('X');
else printf("X^%d",q->exp);
q = q->next;
}
}
void main(){
polynode *P1 = (polynode*)malloc(sizeof(polynode));
polynode *P2 = (polynode*)malloc(sizeof(polynode));
polynode * CreatPolyn(polynode *P,int m);
polynode *polyadd(polynode *pa,polynode *pb);
void PrintfPoly(polynode *P);
P1=CreatPolyn(P1,5);
P2=CreatPolyn(P2,5);
P1=add(P1,P2);
PrintfPoly(P1);
}