求两个一元多项式的和
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分1行,分别以指数递降方式输出和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
5 20 -4 4 -5 2 9 1 -2 0
#include<bits/stdc++.h>//万能头文件
using namespace std;
struct node
{
int coef,expon;//系数 指数
struct node *next;
};
int f1,f2;//组数
int main(void){
node *heada,*headb,*headc,*a,*b,*c;
heada=new node();
headb=new node();
heada->next=NULL;
headb->next=NULL;
b=heada;
cin>>f1;
for (int i=0;i<f1;i++){
a=new node();
cin>>a->coef>>a->expon;
a->next=b->next;
b->next=a;
b=a;
}
b=headb;
cin>>f2;
for (int i=0;i<f2;i++){
a=new node();
cin>>a->coef>>a->expon;
a->next=b->next;
b->next=a;
b=a;
}//两个链表已建好
a=heada->next;
b=headb->next;
headc=new node();
c=headc;
headc->next=NULL;
int num;
while (a&&b){//进行指数比较
if (a->expon>b->expon){
c->next=a;
c=a;
a=a->next;
}
else if (a->expon<b->expon){
c->next=b;
c=b;
b=b->next;
}
else {
num=a->coef+b->coef;
if (num==0){
a=a->next;
b=b->next;
}
else {
a->coef=num;
c->next=a;
c=a;
a=a->next;
b=b->next;
}
}
}
if (a)c->next=a;//指向较长的链的剩余部分
if (b)c->next=b;
int sum=0;//最后一个输出没有空格
while (headc->next!=NULL){
headc=headc->next;
sum++;
if (sum==1)
cout<<headc->coef<<" "<<headc->expon;
else
cout<<" "<<headc->coef<<" "<<headc->expon;
}
if (sum==0)
cout<<"0 0";
}
结果如下
请高手指点