#include
#include
#include
#define M 20
typedef struct Term
{
float coef; //係數
int exp; //指數
struct Term * link; //指針
}pNode,* Polynomial;ide
//創建多項式,帶有頭節點
Polynomial createPoly(int n)
{
Polynomial head, p , pre ,s;
float c; //c爲係數
int e,i = 0; //e爲指數指針
printf("創建多項式單鏈表\n");
head = (Polynomial)malloc(sizeof(pNode));
head->coef = -1;
head->link = NULL;get
while(i < n){
printf("輸入第%d項\n",++i);
scanf("%f%d",&c,&e);
if( c == 0){
printf("輸入的係數爲零!\n");
break;
}
s = (Polynomial)malloc(sizeof(pNode));
s ->coef = c;
s ->exp = e;
p = head;
pre = NULL;
while(p != NULL && p->exp < e){
pre = p;
p = p->link;
}
if(p != NULL && p->exp == e)
printf("輸入項的指數重複\n");
else{
s ->link = p;
pre ->link =s;
}
}
return head;
}it
//多項式顯示
void printPoly(Polynomial poly,int n)
{
Polynomial s;
int i = 1;class
s = poly;
s = s->link;
while(i
printf("%.f*x^%d+",s->coef,s->exp);
s = s->link;
i ++;
}
printf("%.f*x^%d",s->coef,s->exp);
printf("\n");
}float
//多項式的插入
void Insert(Polynomial &poly, float c ,int e,int &n)
{
Polynomial s = poly, t = NULL, p;鏈表
while(s != NULL && s->exp < e)
{
t = s;
s = s->link;
}
if(s != NULL && s ->exp == e){//相同指數,係數合併
if(s ->coef + c != 0){
s ->coef = s->coef + c;
}
else
{
t ->link = s->link;
free(s);
n--;//係數之和爲0,項數減1
}
}
else{
p = (Polynomial)malloc(sizeof(pNode));
p ->exp = e;
p ->coef = c;
if(t == NULL)
{
p ->link =poly;
poly = p;
}
else{
t ->link = p;
p ->link = s;
}
n++;
}
}di
//多項式乘法實現
Polynomial Mul(Polynomial a, Polynomial b, int &n)
{
Polynomial s,t,result;
n = 0;
result = (Polynomial)malloc(sizeof(pNode));
result ->exp = -1;
result ->link = NULL;
t = b->link;
while(t !=NULL){
s = a->link;
while(s != NULL){
Insert(result,s->coef*t->coef,s->exp+t->exp,n);
s = s->link;
}
t = t->link;
}
return result;
}
void main()
{
int n;
Polynomial mul;view
printf("請輸入多項式的項數:");
scanf("%d",&n);
Polynomial poly = createPoly(n);
printf("當前多項式爲:");
printPoly(poly,n);
printf("插入指數爲1,係數爲1的項\n");
Insert(poly,1,1,n);
printPoly(poly,n);
printf("多項式相乘\n");
mul = Mul(poly,poly,n);
printPoly(mul,n);
getch();
}vi