#include <stdio.h>
#include <iostream>
using namespace std
;
typedef struct node
{
double coef
;
int exp
;
node
* next
;
}*poly
;
void initPoly(poly
& p
) {
p
= new node
[1];
p
->next
= NULL;
}
void createPoly(poly
& p
) {
poly lastPtr
= p
;
int exp
;
double coef
;
cout
<< "请输入多项式的指数:(输入的数为负数代表输入完毕)" << endl
;
cin
>> exp
;
cout
<< "请输入多项式的系数:" << endl
;
cin
>> coef
;
while (exp
>= 0) {
poly newItem
= new node
[1];
newItem
->exp
= exp
;
newItem
->coef
= coef
;
newItem
->next
= lastPtr
->next
;
lastPtr
->next
= newItem
;
lastPtr
= newItem
;
cout
<< "请输入多项式的指数:(输入的数为负数代表输入完毕)" << endl
;
cin
>> exp
;
cout
<< "请输入多项式的系数:" << endl
;
cin
>> coef
;
}
cout
<< "多项式创建完毕" << endl
;
}
void displayPoly(poly p
) {
p
= p
->next
;
while (p
) {
cout
<< p
->coef
<< "x^" << p
->exp
;
if (p
->next
&&p
->coef
>0) {
cout
<< "+";
}
p
= p
->next
;
}
}
void polyAdd(poly p1
, poly p2
) {
poly prep1
;
prep1
= p1
;
p1
= p1
->next
;
p2
= p2
->next
;
while (p1
&& p2
) {
if (p1
->exp
== p2
->exp
) {
if (p1
->coef
+ p2
->coef
!= 0) {
p1
->coef
+= p2
->coef
;
p1
= p1
->next
;
p2
= p2
->next
;
prep1
= prep1
->next
;
}
else {
prep1
->next
= prep1
->next
->next
;
delete p1
;
p1
= prep1
->next
;
p2
= p2
->next
;
}
}
else if (p1
->exp
> p2
->exp
) {
p1
= p1
->next
;
prep1
= prep1
->next
;
}
else if (p1
->exp
< p2
->exp
) {
poly temp
= p2
->next
;
p2
->next
= prep1
->next
;
prep1
->next
= p2
;
p2
= temp
;
prep1
= prep1
->next
;
}
}
if (p2
) {
prep1
->next
= p2
;
}
}
int main() {
poly p1
;
poly p2
;
initPoly(p1
);
initPoly(p2
);
createPoly(p1
);
createPoly(p2
);
polyAdd(p1
, p2
);
displayPoly(p1
);
return 1;
}
在这里插入代码片
运行结果如图: 缺点:运行结果格式并不完美,待改进!!
转载请注明原文地址: https://lol.8miu.com/read-23837.html