繁体   English   中英

链表中多项式的导数

[英]derivative of the polynomial in a linked list

出于某种原因,当我试图做我的衍生物时,它只是对一个项目的导数而不是整个多项式。

struct term{
    double coef;
    unsigned deg;
    struct term * next;
    };

我有一个结构,然后还有一个类Polynomial与深拷贝构造函数和=构造函数。 在私人课堂上,我有一个term* ptr

这是我的衍生代码

void Polynomial::derivative (Polynomial *p){
    term *x;
    if ( ptr == NULL)
        return ;
    term *temp;
    temp = ptr;
    while (temp != NULL){
       if ( ptr == NULL){
            ptr = new term ;
            x = ptr ;
        }
        else{
            x -> next = new term ;
            x = x -> next ;
        }
        x-> coef = temp -> coef * temp -> deg;
        x-> deg = temp -> deg - 1;
        temp = temp -> next;

    }
    ptr=x;
}

所以,当我尝试导出3x^4 + 3x^4 + 6x^7 + 3x^4 + 3x^4 + 6x^7 + 2x^9得到18x^8

我正在查看代码,并且不知道为什么它会在最后一个术语中执行此操作,因为它是一个while循环,应该从开始到NULL并执行派生。

由于这两行,你得到了最后一个词:

在你的其他条件:

x = x -> next

和你的最终任务:

ptr = x;

因此,这也会泄漏内存,因为之前分配的那些漂亮的术语现在都在以太中。 无论如何,你正在泄漏旧的,所以无论如何这真的需要重新考虑。

我强烈建议您,因为您的Polynomial类支持完整的复制构造和赋值操作,您可以这个创建一个新的导数多项式,并返回 如果调用者希望这个变换,他们可以poly = poly.derivative(); 他们自己。

微分发生器的例子(与变压器相对)。 作为奖励,在生成衍生产品时消除所有常数项。

Polynomial Polynomial::derivative() const
{
    Polynomial poly;

    const term *p = ptr;
    while (p)
    {
        if (p->deg != 0) // skip constant terms 
        {
            // add term to poly here (whatever your method is called)
            poly.addTerm(p->coef * p->deg, p->deg-1);
        }
        p = p->next;
    }
    return poly;
}

这允许这种生成:(注意p1由derivative()改变):

Polynomial p1;
... populate p1...
Polynomial p2prime = p1.derivative();

对于非常有趣的事情:

Polynomial p1;
... populate p1...
Polynomial p2prime2 = p1.derivative().derivative();

无论如何,我希望这是有道理的。

PolyNodeN* makeDerivate(PolyNodeN* poly)
{
    PolyNodeN* head = new PolyNodeN();
    PolyNodeN* tmp = new PolyNodeN();
    int a = poly->exp;

    int * results = new int[a];
    int * exponents = new int[a];

    for (int i = 0; i < a; i++)
    {
        results[i] = exponents[i] = 0;
    }
    for (poly; poly != nullptr; poly = poly->next)
    {
        results[poly->exp - 1] = poly->koef*poly->exp;
        exponents[poly->exp - 1] = poly->exp - 1;
    }
    head = new PolyNodeN(exponents[a - 1], results[a - 1]);
    tmp = head;

    for (int i = a - 2; i >= 0; i--)
    {
        tmp->next= new PolyNodeN(exponents[i], results[i],tmp);
        tmp = tmp->next;
    }
    tmp->next = nullptr;
    return head;
}

哪个派生? 简单......

PolyNodeN* makeDerivate2(PolyNodeN* poly,int ext)
{
    PolyNodeN* temp = new PolyNodeN();
    temp = temp->makeDerivate(poly);
    for (int i = ext-1; i > 0; i--)
        temp = temp->makeDerivate2(temp, i);
    return temp;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM