[英]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.