[問題] 用linked list算兩個多項式相乘的問題
以下是我寫的一個函式
是要算兩多項式相乘
可是輸入進去的值算出來都是錯的= =
請問我哪個地方需要修正呢?
node *polyMultiply(node *poly1, node *poly2)
{
node *tail, *head, *ptr1, *ptr2, *ptrMultiply;
ptr1=poly1;
ptr2=poly2;
head=tail=NULL;
while(ptr1!=NULL && ptr2!=NULL)
{
ptrMultiply=malloc(sizeof(node));
if(ptr1->exp > ptr2->exp)
{
ptrMultiply->coef = ptr1->coef * ptr2->coef;
ptrMultiply->exp = ptr1->exp + ptr2->exp;
ptr1 = ptr1->next ;
}
else if(ptr1->exp < ptr2->exp)
{
ptrMultiply->coef = ptr2->coef * ptr1->coef;
ptrMultiply->exp = ptr2->exp + ptr1->exp;
ptr2 = ptr2->next ;
}
else
{
ptrMultiply->coef = ptr1->coef + ptr2->coef ;
ptrMultiply->exp = ptr1->exp ;
ptr1 = ptr1->next ;
ptr2 = ptr2->next ;
}
ptrMultiply->next=NULL;
if (head==NULL)
head=ptrMultiply;
else
tail->next=ptrMultiply;
tail=ptrMultiply;
}
if(ptr1==NULL)
{
while(ptr2!=NULL)
{
ptrMultiply=malloc(sizeof(node));
ptrMultiply->coef = ptr2->coef;
ptrMultiply->exp = ptr2->exp;
ptr2 = ptr2->next;
tail->next = ptrMultiply;
tail = ptrMultiply;
}
}
else
{
while(ptr1!=NULL)
{
ptrMultiply=malloc(sizeof(node));
ptrMultiply->coef = ptr1->coef;
ptrMultiply->exp = ptr1->exp;
ptrMultiply = ptr1->next;
tail->next = ptrMultiply;
tail = ptrMultiply;
}
}
return head;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.44.201.220
→
11/12 09:41, , 1F
11/12 09:41, 1F
推
11/12 13:21, , 2F
11/12 13:21, 2F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章