求两个一元多项式的和

求两个一元多项式的和

输入格式:
输入分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";
}

结果如下

pta

请高手指点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值