-2
Самый простой способ получить мой результат, чтобы не выводить 0x^3
? Также как выглядит мой код? Есть ли улучшения, которые я мог бы сделать здесь.Добавление многочленов, используя связанный список
Первый полином:
2x^4 + 3x^3 -7
Второй многочлен:
-5x^5 -2x^4 -7x^2 + 5x^1 -6
Результирующая полином:
-5x^5 **0x^4** + 3x^3 -7x^2 + 5x^1 -13
Код:
#include <iostream>
using namespace std;
class poly
{
private :
struct node
{
float coeff ;
int exp ;
node *link ;
} *p ;
public :
poly() ;
void input (float c, int e) ;
void display() ;
void add(poly &eq1, poly &eq2) ;
~poly() ;
};
poly :: poly()
{
p = NULL ;
}
void poly :: input (float c, int e)
{
node *temp = p ;
if (temp == NULL)
{
temp = new node ;
p = temp ;
}
else
{
while (temp -> link != NULL)
temp = temp -> link ;
temp -> link = new node ;
temp = temp -> link ;
}
temp -> coeff = c ;
temp -> exp = e ;
temp -> link = NULL ;
}
void poly :: display()
{
node *temp = p ;
int f = 0 ;
cout << endl ;
while (temp != NULL)
{
if (f != 0)
{
if (temp -> coeff > 0)
cout << " + " ;
else
cout << " " ;
}
if (temp -> exp != 0)
cout << temp -> coeff << "x^" << temp -> exp ;
else
cout << temp -> coeff ;
temp = temp -> link ;
f = 1 ;
}
}
void poly :: add (poly &eq1, poly &eq2)
{
node *tnode ;
node *temp1, *temp2 ;
if (eq1.p == NULL && eq2.p == NULL)
return ;
temp1 = eq1.p ;
temp2 = eq2.p ;
while (temp1 != NULL && temp2 != NULL)
{
if (p == NULL)
{
p = new node ;
tnode = p ;
}
else
{
tnode -> link = new node ;
tnode = tnode -> link ;
}
if (temp1 -> exp < temp2 -> exp)
{
tnode -> coeff = temp2 -> coeff ;
tnode -> exp = temp2 -> exp ;
temp2 = temp2 -> link ;
}
else
{
if (temp1 -> exp > temp2 -> exp)
{
tnode -> coeff = temp1 -> coeff ;
tnode -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
}
else
{
if (temp1 -> exp == temp2 -> exp)
{
tnode -> coeff = temp1 -> coeff + temp2 -> coeff ;
tnode -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
temp2 = temp2 -> link ;
}
}
}
}
while (temp1 != NULL)
{
if (p == NULL)
{
p = new node ;
tnode = p ;
}
else
{
tnode -> link = new node ;
tnode = tnode -> link ;
}
tnode -> coeff = temp1 -> coeff ;
tnode -> exp = temp1 -> exp ;
temp1 = temp1 -> link ;
}
while (temp2 != NULL)
{
if (p == NULL)
{
p = new node ;
tnode = p ;
}
else
{
tnode -> link = new node ;
tnode = tnode -> link ;
}
tnode -> coeff = temp2 -> coeff ;
tnode -> exp = temp2 -> exp ;
temp2 = temp2 -> link ;
}
tnode -> link = NULL ;
}
poly :: ~poly()
{
node *temp ;
while (p != NULL)
{
temp = p -> link ;
delete p ;
p = temp ;
}
}