回复 4楼 qunxingw
我是在vs2008里弄的,麻烦你啦
#include<iostream>
#include<cmath>
using namespace std;
typedef struct node{
float a;
int b;
struct node *next;
}lnode,*linklist;
linklist creat_linklist(linklist H,int k){
lnode *p,*r,*s;
H=r=NULL;
for(int i=1;i<=k;i++){
p=new lnode;
if(!p){cout<<"分配空间错误!"<<endl; exit(1);}
cout<<"请输入第"<<i<<"项"<<"系数";
cin>>p->a;
cout<<"请输入第"<<i<<"项"<<"指数";
cin>>p->b;
cout<<endl;
if(H==NULL){
H=p;
}
else{
r->next=p;
}
r=p;
}
s=H;
for(int i=1;i<=k;i++){
if(i>1&&s->a>0){
cout<<"+"<<s->a<<"x^"<<s->b;
}
else
cout<<s->a<<"x^"<<s->b;
s=s->next;
}
cout<<endl;
return H;
}
void output(linklist H){
lnode *s=NULL;
s=H;
while(s){
if(s!=H&&s->a>0)
cout<<"+"<<s->a<<"x^"<<s->b;
else
cout<<s->a<<"x^"<<s->b;
s=s->next;
}
}
linklist add(linklist H1,linklist H2){
linklist H3=NULL;
lnode *s1,*s2;
lnode *pre=NULL;
s1=H1;
s2=H2;
pre=H3;
while(s1!=NULL&&s2!=NULL){
if(s1->b==s2->b){
pre=new lnode;
pre->a=s1->a+s2->a;
pre->b=s1->b;
pre=pre->next;
s1=s1->next;
s2=s2->next;
}
else if(s1->b<s2->b){
pre=new lnode;
pre->a=s1->a;
pre->b=s1->b;
s1=s1->next;
pre=pre->next;
}
else
{
pre=new lnode;
pre->a=s2->a;
pre->b=s2->b;
pre=pre->next;
s2=s2->next;
}
}
while(s1!=NULL||s2!=NULL){
if(s1!=NULL){
pre=new lnode;
pre=s1;
}
else{
pre=new lnode;
pre=s2;
}
}
cout<<pre->a<<endl;
return H3;
}
int main(){
linklist H1=NULL,H2=NULL,H3=NULL;
int m,n;
cout<<"请输入多项式a的项数";
cin>>m;
creat_linklist(H1,m);
cout<<"请输入多项式b的项数";
cin>>n;
creat_linklist(H2,n);
add(H1,H2);
cout<<"相加后的结果为:";
output(H3);
return 0;
}