最简单的方法是让我的结果不输出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 ;
}
}
答案 0 :(得分:1)
您可以添加一个函数来删除那些0系数。
void poly :: remove_zero () {
node *cnode = p, *pnode = NULL;
while (cnode != NULL) {
if (cnode->coeff == 0) { // remove 0 node
if (pnode == NULL) { // if this is the first node
p = cnode->link;
delete cnode;
cnode = p;
} else { // if this is not the first node
pnode->link = cnode->link;
delete cnode;
cnode = pnode->link;
}
} else {
pnode = cnode;
cnode = cnode->link;
}
}
}