#include
#include
#include
typedef struct Polynomial
{
float coef;
int exp;
struct Polynomial *next;
}*Poly,Polynomial;
void Insert(Poly p,Poly head) //插入
{
if(p->coef==0) //系数为0时释放结点
free(p);
else
{
Poly q1,q2;
q1=head;
q2=head->next;
while(q2&&p->exp
{
q1=q2;
q2=q2->next;
}
if(q2&&p->exp==q2->exp) //将指数相同的相合并
{
q2->coef+=p->coef;
free(p);
if(!q2->coef) //系数为0时释放结点
{
q1->next=q2->next;
free(q2);
}
//p->next=q2;
//q1->next=p;
}
else
{
p->next=q2;
q1->next=p;
}
}
}
Poly CreateList(Poly head,int m) //建立一个头指针为head、项数为m的一元多项式
{
int i;
Poly p;
Polynomial *q;
p=head=(Poly)malloc(sizeof(struct Polynomial));
head->next=NULL;
for(i=0;i
p=(Poly)malloc(sizeof(struct Polynomial)); //建立新结点以接收数据
cout<<"请输入第"< cin>>p->coef>>p->exp;
Insert(p,head); //调用Insert函数插入结点
}
return head;
}
int OutputList(Poly P) //输出多项式
{
Poly q=P->next;
int flag=1; //项数计数器
if(!q)
{ //若多项式为空,输出0
cout<<" 0 "<
}
while (q)
{
if(q->coef>0&&flag!=1) //系数大于0且不是第一项
cout<<"+";
if(q->coef!=1&&q->coef!=-1) //系数非1或-1的普通情况
{
cout<
if(q->exp==1)
cout<<"X";
else if(q->exp)
cout<<"X^"<
}
else
{
if(q->coef==1)
{
if(!q->exp)
cout<<"1";
else if(q->exp==1)
cout<<"X";
else if(q->exp)
cout<<"X^"<
}
if(q->coef==-1)
{
if(!q->exp) cout<<"-1";
else if(q->exp==1) cout<<"-X";
else cout<<"-X^"<
}
}
q=q->next;
flag++;
}
cout<
}
int compare(Poly a,Poly b)
{
if(a&&b)
{
if(!a||a->exp>b->exp) return 1;
else if(!b||a->exp
else return 0;
}
else if(!a&&b) return -1; //a多项式已空,但b多项式非空
else return 1; //b多项式已空,但a多项式非空
}
Poly AddPoly(Poly pa,Poly pb) //求解并建立和多项式a+b,返回其头指针
{
Poly qa=pa->next;
Poly qb=pb->next;
Poly headc,hc,qc;
hc=(Poly)malloc(sizeof(struct Polynomial)); //建立头结点
hc->next=NULL;
headc=hc;
while(qa||qb)
{
qc=(Poly)malloc(sizeof(struct Polynomial));
switch(compare(qa,qb))
{
case 1:
{
qc->coef=qa->coef;
qc->exp=qa->exp;
qa=qa->next;
break;
}
case 0:
{
qc->coef=qa->coef+qb->coef;
qc->exp=qa->exp;
qa=qa->next;
qb=qb->next;
break;
}
case -1:
{
qc->coef=qb->coef;
qc->exp=qb->exp;
qb=qb->next;
break;
}
}
if(qc->coef!=0)
{
qc->next=hc->next;
hc->next=qc;
hc=qc;
}
else free(qc); //当相加系数为0时,释放该结点
}
return headc;
}
int main()
{
int m,n,flag=0;
float x;
Poly pa=0,pb=0,pc,pd,pe,pf; //定义各式的头指针,pa与pb在使用前付初值NULL
cout<<" 输入多项式a和b: "< cout<<"请输入a的项数:" ; //建立多项式a cout<<"请输入b的项数:" ; //建立多项式b cout< cout<<"***************************************"< cout<<" 1.输出多项式a "< cout<<"***************************************"< if(flag<0||flag>7)
cin>>m;
if(!cin)
{
cout<
cout<
pa=CreateList(pa,m);
cin>>n;
if(!cin)
{
cout<
cout<
pb=CreateList(pb,n);
OutputList(pb);
{
cout<<"执行操作为:" ;
cin>>flag;
if(flag==1)
{
if(pa)
{
cout<<"多项式a为:";
OutputList(pa);
}
else
{
cout<<"0"<
continue;
}
if(flag==2)
{
cout<<"多项式b为:";
OutputList(pb);
continue;
}
if(flag==3)
{
pc=AddPoly(pa,pb);
cout<<"多项式a+b为:";
OutputList(pc);
continue;
}
if(flag==0)
break;
cout<<"输入错误!!!请重新选择!!";
continue;
}
return 0;
}