2012-03-09 15 views
0

+我有你輸入一個多項式(係數和指數)與係數,指數的S結構鏈表一個項目,一個指向下一個節點。我有存儲設置,但是與操作員有問題。我已經有了所有的設定,但超出了即時通訊有問題。算子鏈表ADT

到目前爲止,我有

Poly Poly::operator+ (const Poly& orig){ 
    bool firstTime = 0; 
    Poly temp; 
    temp.Head = new PolyTerm; 
    temp.Size = 1; 
    ptrType New = temp.Head; 
    ptrType cur = Head; 
    for(int i = 1; i <= Size; i++) { 
      ptrType org = orig.Head; 
      for(int j = 1; i <= orig.ListLength(); j++) { 
        if(org->exp == cur->exp) { 
          if(firstTime) { 
            New->Next = new PolyTerm; 
            New = New->Next; 
            New->Next = NULL; 
            temp.Size += 1; 
          } 
          New->coef = ((cur->coef) + (org->coef)); 
          New->exp = cur->exp; 
          firstTime = 1; 
          break; 
        } 
        org = org->Next; 

      } 
      cur = cur->Next; 
    } 

    return temp; 
} 

它看上去一切正常,並用破發點,它會返回和回報,但在那之後我的程序掛起。林不知道我做錯了,但我認爲這是簡單

我希望我已經提供了足夠的信息。隨意問的東西

+0

'firstTime'最初是'false'。你不會輸入'if()'condition firstTime。那是你要的嗎? – noMAD 2012-03-09 19:27:29

+0

是的,這就是我想要的,它應該只發生在第一次後 – Brian 2012-03-09 19:48:21

+0

@BrianMcNamara:也許這應該被稱爲「notFirstTime」呢? (並初始化爲'false') – 2012-03-09 20:37:11

回答

0

我不知道你是怎麼定義的多型。 這是我會做的:poly類型存儲多項式的值,如int存儲一個數字。 (您可能也想實現運算符==。)

#include <memory> 

template<typename COEF,typename EXP> 
struct PolyList { 
    COEF coef; 
    EXP exp; 
    std::shared_ptr<const PolyList<COEF,EXP>> next; 
    template<typename C,typename E> 
    PolyList(C coef,E exp):coef(coef),exp(exp){} 
}; 

template<typename COEF,typename EXP> 
struct poly : public std::shared_ptr<const PolyList<COEF,EXP>> { 
    template<typename X> 
    poly(X x):std::shared_ptr<const PolyList<COEF,EXP>>(x){} 
    poly(){} 
}; 

template<typename COEF,typename EXP> 
poly<COEF,EXP> operator+(poly<COEF,EXP> a,poly<COEF,EXP> b) 
{ 
    if(!a) return b; 
    if(!b) return a; 
    if(a->exp > b->exp){ 
     PolyList<COEF,EXP> *ret = new PolyList<COEF,EXP>(a->coef,a->exp); 
     ret->next = a->next + b; 
     return ret; 
    } 
    if(a->exp < b->exp) return b+a; 
    // a->exp == b->exp 
    COEF c = a->coef + b->coef; 
    if(!c) return a->next + b->next; 
    // c!=0 
    PolyList<COEF,EXP> *ret = new PolyList<COEF,EXP>(c,a->exp); 
    ret->next = a->next + b->next; 
    return ret; 
}