[英]overloading + operator in a polynomial linked list
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
insert函数按从高到低的排序顺序添加术语
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
. 如果指针之一是
nullptr
,则最终将取消引用nullptr
。
I would try 我会尝试
while(current != nullptr && temp != nullptr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.