so i am trying to overload the + operator in a single linked list the problem is that my program crashes each time i try to run the code.in my code i tried to add the coefficients with the same exponent.And in case the exponents are not equal i tried to add the different two terms to the resulting polynomial. The insert function adds the term in a sorted order from higher exponent to lower one
polynomials polynomials:: operator + (const polynomials&p )const{
node*current=head;
node*temp=p.head;
polynomials poly;
node *newnode=0;
while(current!=0||temp!=0)
{
if(current->exponent==temp->exponent)
{
newnode->exponent=current->exponent;
newnode->coefficient=current->coefficient+temp->coefficient;
poly.insert(*newnode);
newnode=newnode->link;
}
else
{
if(current->exponent > temp->exponent)
{ newnode->exponent=current->exponent;
newnode->coefficient=current->coefficient;
poly.insert(*newnode);
newnode=newnode->link;
newnode->exponent=temp->exponent;
newnode->coefficient=temp->coefficient;
poly.insert(*newnode);
}
else
{
newnode->exponent=temp->exponent;
newnode->coefficient=temp->coefficient;
poly.insert(*newnode);
newnode=newnode->link;
newnode->exponent=current->exponent;
newnode->coefficient=current->coefficient;
poly.insert(*newnode);
}
}
current=current->link;
temp=temp->link;
}
return poly;}
One problem I see.
while(current!=0||temp!=0)
followed by
if(current->exponent==temp->exponent)
is not right. If one of the pointers is nullptr
, you end up dereferencing a nullptr
.
I would try
while(current != nullptr && temp != nullptr)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.