运算符+与链表ADT

时间:2012-03-09 19:19:06

标签: c++

我有一个项目,您可以将多项式(Coefficient和exponent)导入到一个链接列表中,该链接列表的结构为Coefficient,Exponent和指向下一个节点的指针。我有所有设置的存储,但我遇到了运营商的问题。我已经得到了=所有设置但超出了我有问题。

到目前为止我已经

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;
}

它似乎运行正常并且有断点它会返回并返回,但我的程序在此之后挂起。我不确定我做错了什么,但我认为这很简单

我希望我提供了足够的信息。随意问一些事情

1 个答案:

答案 0 :(得分:0)

我不知道你是如何定义Poly类型的。 这就是我要做的:poly类型存储多项式的值,如int存储一个数字。 (您可能也希望实现operator ==。)

#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;
}