[Description of Problem] Write a program to store polynomials with a singly linked list and implement the function of adding two unary polynomials A and B. A and B are initially in ascending order, and the sum of A and B is in descending order. For example:
Polynomial A: 1.2X ^ 0 2.5X ^ 1 3.2X ^ 3 -2.5X ^ 5
Polynomial B: -1.2X ^ 0 2.5X ^ 1 3.2X ^ 3 2.5X ^ 5 5.4X ^ 10
Polynomials A and B Sum: 5.4X ^ 10 6.4X ^ 3 5X ^ 1
【Input form】 Any two polynomials A and B
[Output form] The coefficient and exponent of a term in the polynomial, the coefficient retains one decimal place.
[Sample input] 1.2 0 2.5 1 3.2 3 -2.5 5
-1.2 0 2.5 1 3.2 3 2.5 5 5.4 10
2
[Sample output] 6.4 3
[Sample description] The first polynomial coefficient and exponent pair are separated by a space. The
second polynomial coefficient and exponent pair are separated by a space and
the second term coefficient and exponent are output. The coefficient and exponent are separated by a space , The coefficient retains a decimal
[Scoring criteria] must be implemented with a linked list.
#include <iostream>
#include <cstdio>
using namespace std;
struct Node
{
float coef;
int exp;
Node *next;
};
class Polynomial
{
public:
Polynomial();
Polynomial(const Polynomial &B);
Polynomial operator+ (Polynomial &B);
void Printk(int k);
void Print();
private:
Node *first;
};
Polynomial :: Polynomial()
{
Node* r =NULL, * s=NULL;
first = new Node;
r=first;
char c;
do
{
s=new Node;
scanf("%f%d", &s->coef, &s->exp);
r->next=s;
r=s;
c=getchar();
}while(c != EOF&& c != '\n');
r->next=NULL;
}
Polynomial::Polynomial(const Polynomial &B)
{
first=B.first;
}
Polynomial Polynomial:: operator+(Polynomial &B)
{
Node *pre =first,*p=pre->next;
Node *qre=B.first,*q=qre->next;
while(p && q)
{
if(p->exp < q->exp)
{
pre=p;
p=p->next;
}
else if(p->exp > q->exp)
{
qre->next=q->next;
q->next=p;
pre->next=q;
pre=q;
q=qre->next;
}
else
{
p->coef = q->coef+p->coef;
if(p->coef==0)
{
pre->next = p->next;
delete p;
p=pre->next;
}
else
{
pre=p;
p=p->next;
}
qre->next=q->next;
delete q;
q=qre->next;
}
}
if(q) pre->next = q;
return *this;
}
void Polynomial::Print()
{
Node *p=first->next;
if(p)
cout<<p->coef<<"x"<<p->exp;
p=p->next;
while(p)
{
if(p->coef>0)
cout<<"+"<<p->coef<<"x"<<p->exp;
else
cout<<p->coef<<"x"<<p->exp;
p=p->next;
}
}
void Polynomial::Printk(int k)
{
Node* p=first;
int cnt = 0;
while (p&&cnt < k)
{
p= p->next;
cnt++;
}
Node* prek=first;
while(p)
{
p=p->next;
prek = prek->next;
}
printf("%.1f %d",prek->coef,prek->exp);
}
int main()
{
Polynomial A,B;
//A.Print();B.Print();
A = A+B;
//cout<<"½á¹ûÊÇ:";
//A.Print();
int k;
cin>>k;
A.Printk(k);
return 0;
}