簡體   English   中英

多項式鏈表中的重載+運算符

[英]overloading + operator in a polynomial linked list

所以我試圖在單個鏈表中重載+運算符,問題是每次我嘗試運行代碼時我的程序都崩潰了。在我的代碼中,我試圖添加具有相同指數的系數。不相等,我嘗試將不同的兩個項加到所得多項式中。 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;}

我看到一個問題。

while(current!=0||temp!=0) 

其次是

if(current->exponent==temp->exponent)

是不正確的。 如果指針之一是nullptr ,則最終將取消引用nullptr

我會嘗試

while(current != nullptr && temp != nullptr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM