课程实验,不足之处请指出
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Polynode
{
int coef;
int exp;
struct Polynode *next;
}Polynode,*Polylist;
Polylist PolyCreate()
{
Polynode *head,*rear,*s;
int c,e;
head=(Polynode*)malloc(sizeof(Polynode));
rear=head;
scanf("%d,%d",&c,&e);
while(c!=0)
{
s=(Polynode*)malloc(sizeof(Polynode));
s->coef=c;
s->exp=e;
rear->next=s;
rear=s;
scanf("%d,%d",&c,&e);
}
rear->next=NULL;
return(head);
}
void PolyAdd(Polylist polya,Polylist polyb)
{
Polynode *p,*q,*tail,*temp;
int sum;
p=polya->next;
q=polyb->next;
tail=polya;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
tail->next=q;tail=p;p=p->next;
}
else if((p->exp)==(q->exp))
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
tail->next=p;
tail=p;
p=p->next;
temp=q;
q=q->next;
free(temp);
}
else
{
temp=p;p=p->next;free(temp);
temp=q;q=q->next;free(temp);
}
}
else
{
tail->next=q;tail=q;q=q->next;}
}
if(p!=NULL)
tail->next=p;
else
tail->next=q;
}
void Subtract(Polylist polya,Polylist polyb)
{
Polynode *p,*q,*tail,*temp;
int sum;
p=polya->next;
q=polyb->next;
tail=polya;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
tail->next=p; tail=p; p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef-q->coef;
if(sum!=0)
{
p->coef=sum;
tail->next=p;
tail=p;
p=p->next;
temp=q;q=q->next; free(temp);
}
else
{
temp=p; p=p->next; free(temp);
temp=q; q=q->next; free(temp);
}
}
else
{
tail->next=q; tail=q;
q=q->next;
}
}
if(p!=NULL)
tail->next=p;
else
tail->next=q;
}
void Print(Polylist v)
{
Polylist s=v->next;
int i=0;
if(s)
printf("f(x)=");
else
printf("f(x)=0\n");
while(s)
{ i=0;
printf("%d",s->coef);
while(i<abs(s->exp))
{
if(!(s->exp));
else
s->exp>0?printf("*x"):printf("/x");
i++;
}
if(s->next&&s->next->coef>=0)
printf("+");
s=s->next;
}
putchar(’\n’);
}
int main()
{
Polylist p,q;
int flag=1;
char c;
while(flag)
{
printf("1.create polylist\n");
printf("2.add\n");
printf("3.substract\n");
printf("p.print polylist\n");
printf("q.quit\n");
c=getchar();
switch(c)
{
case’1’:{printf("Creating the list.1 please input number:(for example (1,2))\n");
p=PolyCreate();
Print(p);
printf("Creating the list.2 please input number:(for example (1,2))\n");
q=PolyCreate();
Print(q);break;}
case’2’:printf("adding\n");
PolyAdd(p,q);break;
case’3’:printf("subtracting\n");
Subtract(p,q);break;
case’p’:printf("the result is : ");
Print(p);
case’q’:flag=0;
}
}
return 0;
}