以前写的代码。。
#include<iostream>
using namespace std;
#define max 10000000
struct node
{
float coef;
int exp;
node *next;
};
struct Poly
{
char name;
node *other;
}poly[max];
int count;//poly的个数;
//生成多项式的函数
void creat(node *&L)
{
node *p,*q;
L=new node;
q=L;
float a;
int b;
while(cin>>a>>b)
{
if((a==0&&b<0)||b<0) break;
p=new node;
p->coef=a;
p->exp=b;
q->next=p;
q=p;
}
q->next=NULL;
}
//输入多项式
void inputing()
{
char c,d;
node *L;
do
{
cout<<"要输入多项式请按‘Y’,放弃请按其他键"<<endl;
cin>>c;
cin.get();
if(c=='Y')
{
count++;
cout<<"请输入要输入多项式的名字(仅一个字符):";
cin>>d;
cin.get();
poly[count].name=d;
cout<<"请按指数由小到大的顺序输入系数和对应的指数,输入0 -1结束."<<endl;
creat(L);
poly[count].other=L->next;
}
}while(c=='Y');
}
//两个多项式的加法
void adding(int i1,int i2,node *&L)
{
node *L1=poly[i1].other;
node *L2=poly[i2].other;
L=new node;
node *r=L,*s;
while(L1!=NULL&&L2!=NULL)
{
s=new node;
if(L1->exp<L2->exp)
{
s->coef=L1->coef;
s->exp=L1->exp;
r->next=s;
r=s;
L1=L1->next;
}
else if(L1->exp>L2->exp)
{
s->coef=L2->coef;
s->exp=L2->exp;
r->next=s;
r=s;
L2=L2->next;
}
else
{
s->coef=L1->coef+L2->coef;
s->exp=L1->exp;
r->next=s;
r=s;
L1=L1->next;
L2=L2->next;
}
}
while(L1!=NULL)
{
s=new node;
s->coef=L1->coef;
s->exp=L1->exp;
r->next=s;
r=s;
L1=L1->next;
}
while(L2!=NULL)
{
s=new node;
s->coef=L2->coef;
s->exp=L2->exp;
r->next=s;
r=s;
L2=L2->next;
}
r->next=NULL;
}
//多项式的运算
void operating()
{
int n,i;
char c1,c2;
node *L;
printf("1--两个多项式之和\n2--两个多项式之差\n3--数乘\n4--求导\n0--放弃\n");
cout<<"请选择:";
cin>>n;
cin.get();
if(n==1||n==2)
{
if(n==1) cout<<"请输入二个多项式(格式:k=f+g):";
if(n==2) cout<<"请输入二个多项式(格式:k=f-g):";
count++;
cin>>poly[count].name>>c1>>c1>>c2>>c2;
int i1,i2;
for(i=0;i<count;i++)
{
if(c1==poly.name) i1=i;
if(c2==poly.name) i2=i;
}
if(n==2)
{
node *s=poly[i2].other;
while(s!=NULL)
{
s->coef=-s->coef;
s=s->next;
}
}
adding(i1,i2,L);
if(n==2)
{
node *s=poly[i2].other;
while(s!=NULL)
{
s->coef=-s->coef;
s=s->next;
}
}
poly[count].other=L->next;
}
else if(n==3)
{
node *p,*r,*q;
cout<<"请输入数与多项式(格式:k=n*f):";
count++;
cin>>poly[count].name>>c1>>n>>c1>>c2;
for(i=0;i<count;i++)
if(c2==poly.name) break;
L=poly.other;
q=new node;
r=q;
while(L!=NULL)
{
p=new node;
p->coef=n*(L->coef);
p->exp=L->exp;
r->next=p;
r=p;
L=L->next;
}
r->next=NULL;
poly[count].other=q->next;
}
else if(n==4)
{
node *p,*q,*r;
cout<<"请输入要求导的多项式(格式:g=f'):";
count++;
cin>>poly[count].name>>c1>>c1>>c2;
for(i=0;i<count;i++)
if(c1==poly.name) break;
L=poly.other;
q=new node;
r=q;
while(L!=NULL)
{
p=new node;
if(L->exp>0)
{
p->exp=L->exp-1;
p->coef=(L->coef)*(L->exp);
r->next=p;
r=p;
}
L=L->next;
}
r->next=NULL;
poly[count].other=q->next;
}
}
//输出多项式
void display()
{
int i,k,t;
node *p;
for(i=0;i<=count;i++)
{
t=0;
cout<<poly.name<<" = ";
p=poly.other;
k=-1;
while(p!=NULL)
{
t=1;
k++;
if(k==0&&p->exp==0) cout<<p->coef;
else
{
if(p->coef>=0&&k!=0)
cout<<"+";
cout<<p->coef<<"x^"<<p->exp;
}
p=p->next;
}
if(t==0) cout<<"0";
cout<<endl;
}
}