#include<stdio.h>
#include<stdlib.h>
typedef struct node* list;
struct node
{
double coef;
int expon;
list next;
};
list create() //创建
{
int n;
printf("输入多项式的项数:");
scanf("%d", &n);
printf("输入多项式的系数和指数(空格为界):");
list head = (list)malloc(sizeof(struct node)), now = head, last;
for (; n--; now = last)
{
last = (list)malloc(sizeof(struct node));
scanf("%lf%d", &last->coef, &last->expon);
now->next = last;
}
now->next = NULL;
return head;
}
list mul(list a, list b) //相乘
{
list head = (list)malloc(sizeof(struct node)), now = head, last;
for (list i = a->next; i != NULL; i = i->next)for (list j = b->next; j != NULL; j = j->next)
{
last = (list)malloc(sizeof(struct node));
last->coef = i->coef * j->coef; // 系数
last->expon = i->expon + j->expon; // 指数
now->next = last;
now = last;
}
now->next = NULL;
return head;
}
void sort(list a) //排序并且将expon相同的合并
{
if (a->next == NULL || a->next->next == NULL)return;
list r = a, i;
while (r->next->next != NULL)r = r->next;
for (; 1; r = i)
{
if (r != a)
for (i = a; 1; i = i->next)
{
list j = i->next, k = j->next;
if (j->expon < k->expon)
{
if (j == r)r = k;
else if (k == r)r = j;
i->next = k, j->next = k->next, k->next = j;
}
if (i->next == r)break;
}
if (r->next->next != NULL)
{
list j = r->next, k = j->next;
if (j->expon == k->expon)j->coef += k->coef, j->next = k->next;
}
if (r == a)break;
}
}
void show(list a) //输出
{
list i = a->next;
if (i != NULL)
{
printf("%g*x^%d", i->coef, i->expon);
for (i = i->next; i != NULL; i = i->next)if (i->coef)
{
if (i->coef > 0)putchar('+');
printf("%g*x^%d", i->coef, i->expon);
}
}
putchar('\n');
return;
}
int main()
{
list a = create(), b = create(), c = mul(a, b);
show(a);
show(b);
sort(c);
show(c);
return 0;
}
07-14
9376