链表的应用,输入多项式,并求解,简易测试数据,减下方注释的文件。
#include <stdlib.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)
{
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=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;
}
}
int main()
{
Polynode *p1,*p2;
p1=PolyCreate();
p2=PolyCreate();
PolyAdd(p1,p2);
printf("p(x) = ");
while(p1->next != NULL)
{
p1=p1->next;
printf("%dx^%d ",p1->coef,p1->exp);
if(p1->next != NULL)
{
printf("+ ");
}
}
return 0;
}
/*
7 0 3 1 9 8 5 17 0 0
8 1 22 7 -9 8 0 0
*/