#include<iostream>
using namespace std;
class term{
float coef;
int expn;
term *link;//coef为系数,expn为指数
public:
term();
term(const float &data1,const int &data2);
friend class list;
};
term::term(){ link=NULL;}
term::term(const float &data1,const int &data2){
coef=data1;
expn=data2;
link=NULL;
}
class list{
term *head,*tail;
public:
list();
void makeempty();
void deleteterm(term *p);
~list();
term *find(int data);//查找指数相同的项,并返回该项地址
void printlist();
void insertrear(term *p);//向后生成链表,不排序
void insertorder(term *p);//按升序排列
term *creatterm(float data1,int data2);//生成孤立项
};
list::list(){
head=tail=new term();
}
list::~list(){
makeempty();
delete head;
}
void list::makeempty(){
term *tempP;
while(head->link!=NULL){
tempP=head->link;
head->link=tempP->link;
delete tempP;
}
tail=head;
}
term *list::find(int data){
term *tempP=head->link;
while(tempP!=NULL&&tempP->expn!=data) tempP=tempP->link;
return tempP;
}//查找成功返回该地址,不成功则返回NULL
void list::printlist(){
term *tempP=head;
cout<<tempP->coef<<"x^"<<tempP->expn;
tempP=tempP->link;
while(tempP!=NULL){
if(tempP->coef<0) {
cout<<tempP->coef<<"x^"<<tempP->expn;
}
if(tempP->coef>0){
cout<<"+"<<tempP->coef<<"x^"<<tempP->expn;
}
tempP=tempP->link;
}
cout<<endl;
}
void list::deleteterm(term *p){
term *tempP=head;
while(tempP->link!=NULL&&tempP->link!=p) tempP=tempP->link;
if(tempP->link==tail) tail=tempP;
else tempP->link=p->link;
}
term *list::creatterm(float data1,int data2){
term *tempP=new term(data1,data2);
return tempP;
}
void list::insertrear(term *p){
term *tempP=list::find(p->expn);
if(tempP!=NULL) {
if((p->coef+tempP->coef)==0) list::deleteterm(tempP);
else tempP->coef=p->coef+tempP->coef;
}
else{
p->link=tail->link;
tail->link=p;
tail=p;
}
}
void list::insertorder(term *p){
term *tempP=list::find(p->expn);
if(tempP!=NULL) {
if((p->coef+tempP->coef)==0) list::deleteterm(tempP);
else tempP->coef=p->coef+tempP->coef;
}
else{
term *tempQ=head;
term *tempP=head->link;
while((p->expn)>(tempP->expn)&&tempP->link!=NULL){
tempQ=tempP;
tempP=tempP->link;
}
if(p->expn<tempP->expn){
tempQ->link=p;
p->link=tempP;
}
if(p->expn>tempP->expn&&tempP->link==NULL){
tempP->link=p;
p->link=NULL;
}
}
}
int main(){
term *P1;
list list1;
cout<<"请输入一元多项式的项数"<<endl;
float a;
int b;
int n;
int m;
cin>>n;
for(m=0;m<n;m++){
cin>>a>>b>>endl;
P1=list1.creatterm(a,b);
list1.insertorder(P1);
}
list1.printlist();
cout<<"程序结束";
return 0;
}