利用单链表实现两个一元多项式的加法操作
要求:每个多项式按照指数升幂的形式表示
*提示:
1、相同指数幂的系数和为零不存储
2、每个多项式的输入要求先输入项数,然后分别给出系数和对应的指数
Input
5 3 0 4 1 7 8 2 18 1 30
3 5 1 6 3 -7 8
Output
3.0 0 9.0 1 6.0 3 2.0 18 1.0 30 *
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int XS;
int MI;
Node *next;
};
class List
{ Node *first;
public:
List()
{
first =new Node;
first->next=nullptr;
}
~List()
{
Node *p;
while(first)
{ p=first;
first= first->next;
delete p;
}
}
void Insert(int xs,int mi)
{
Node *p,*s;
p=first;
s =new Node;
s->MI =mi;
s->XS =xs;
s->next=nullptr;
while(p->next!=nullptr&&p->next->MI<mi)
{p=p->next;
}
s->next = p->next;
p->next = s;
}
void Merge(List B)
{
Node *p,*s,*l;
p= first->next;
s=B.first->next;
int Y[1000],n=0;
while(p)
{
while(s)
{
if(s->MI == p->MI)
{
p->XS+=s->XS;
Y[n++]=s->MI;
s=s->next;
}
else
{
s=s->next;
}
}
s=B.first->next;
p=p->next;
}
s=B.first->next;
while(s)
{ int g=0;
for(int i=0;i<n;i++)
if(Y[i]==s->MI)g=1;
if(g!=1)
Insert(s->XS,s->MI);
s=s->next;
}
}
void Display()
{
Node *p;
p = first;
while(p->next!=nullptr)
{ p =p->next;
if(p->XS!=0)
{
cout<<p->XS<<".0 "<<p->MI<<" ";
}
}
}
};
int main()
{
List S,B;int a,b,n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a>>b;
S.Insert(a, b);
}
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a>>b;
B.Insert(a, b);
}
S.Merge( B);
S.Display();
}