#include <stdio.h>
#include <stdlib.h>
//定义一元多项式链表
typedef struct Polynode{
int coef;//系数
int exp;//指数
Polynode *next;
}Polynode,*Polylist;
//多项式约定为降次 指数为0时结束
//尾插法建立多项式
Polylist Mult(Polylist p1, Polylist p2);
Polylist polycreate()
{
Polynode * header, *rear ;
int n = 0;
int c, e;
header = (Polynode *)malloc(sizeof(Polynode));//头结点,空的,没有内容,最后要删掉
rear = header;
rear->next = NULL;
printf("请输入多项式的项数:");
scanf("%d", &n);
while (n--)
{
printf("请输入多项式的系数与指数:");
scanf("%d %d", &c, &e);
if (c != 0)
{
Polynode * s = (Polynode *)malloc(sizeof(Polynode));
s->coef = c;
s->exp = e;
rear->next = s;
rear = s;
}
else
{
printf("请重新输入!");
}
}
rear->next = NULL;
return header;
}
void polyadd(Polylist polya, Polylist polyb)
{
Polylist p, q, pre,temp;
int sum = 0;
p = polya->next;
q = polyb->next;
pre = polya;
while ((p != NULL) && (q != NULL))
{
if (p->exp > q->exp)
{
pre->next = p;
pre = pre->next;
p = p->next;
}
else if (p->exp < q->exp)
{
pre->next = q;
pre = pre->next;
q = q->next;
}
else
{
sum = p->coef + q->coef;
if (sum!=0)
{
p->coef = sum;
pre->next = p;
pre = pre->next;
p = p->next;
temp = q;
q = q->next;
free(temp);
}
else
{
temp = p->next;
free(p);
p = temp;
temp = q->next;
free(q);
q = temp;
}
}
}
if (p != NULL)
{
pre->next = p;
}
else
{
pre->next = q;
}
}
void show(Polylist p)
{
Polylist a = p->next;
while (a != NULL&&a->coef != 0)
{
printf("%d %d ", a->coef, a->exp);
a = a->next;
}
}
//传入系数、指数、Polynode *类型的指针
void Attach(int c, int e, Polylist *pRear)
{
Polynode * P;
P = (Polynode *)malloc(sizeof(Polynode));//申请节点
P->coef = c;
P->exp = e;
P->next = NULL;
(*pRear)->next = P;
*pRear=P;
}
Polylist Mult(Polylist p1, Polylist p2)
{
Polylist p, rear, t1, t2, t;
int c, e;
if (p1->next == NULL || p2->next == NULL)
{
printf(" !");
}
t1 = p1->next;//因为p1是带有空头结点的
t2 = p2->next;
p = (Polylist)malloc(sizeof(Polynode));
p->next = NULL;
rear = p;
//先用p1的第一项乘以p2的所有项,得到一串一元多项式
while (t2)
{
Attach(t1->coef*t2->coef, t1->exp + t2->exp, &rear);
t2 = t2->next;
}
//将p1的第二项以后的项乘以p2的所有项,然后插入到第一串得到的结果多项式
t1 = t1->next;
while (t1)
{
t2 = p2->next;
rear = p;//将rear再次放到头部,此时rear是个带有空头结点的单链表
while (t2)
{
e = t1->exp+t2->exp;
c = t1->coef*t2->coef;
//查找插入的位置
while (rear->next&&rear->next->exp > e)
{
rear = rear->next;
}
if (rear->next&&rear->next->exp == e)//Rear的下一项的指数等于要插入的指数,要做合并
{
if (rear->next->coef + c)//系数相加后不等于0,c加进原来的
{
rear->next->coef += c;
}
else//系数相加后等于0,删掉
{
t = rear->next;
rear->next = t->next;
free(t);
}
}
else//Rear的下一项的指数小于要插入的指数,可以插入
{
t = (Polynode *)malloc(sizeof(Polynode));//创建个新节点
t->coef = c;
t->exp = e;
t->next = rear->next;
rear->next = t;
rear = rear->next;
}
t2 = t2->next;
}
t1 = t1->next;
}
第一个空结点要删掉
//t2 = p;
//p = p->next; //指向下一个位置
//free(t2);
return p;
}
int main()
{
Polynode * ps;
Polynode * P = polycreate();
show(P);
printf("\n");
Polynode * Q = polycreate();
show(Q);
/*printf("\n");
polyadd(P, Q);
printf("多项式的和为:\n");
show(P);*/
printf("\n");
ps = Mult(P, Q);
show(ps);
return 0;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交