设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
太恶心了,那个零项式是声明狗意思啊,到底是什么鬼啊;
md,又说零项式输出0 0,又不对,然后我去网上找通过的,结果我看零项式输出毛规律都没有,我真是要吐血了,这个我之通过了第一个节点,后面再改吧;
#include <stdio.h>
#include <stdlib.h>
typedef struct node *list;
struct node
{
int coefficient;
int exponent;
list next;
};
list de(list m);
list swap(list m);
list read();
list multi(list m, list n);
list plus(list m, list n);
list in(list m);
int main()
{
list l1 = NULL, l2 = NULL, l = NULL, m = NULL;
l1 = read();
l2 = read();
l = multi(l1, l2);
m = plus(l1, l2);
printf("%d %d", l->coefficient, l->exponent);
l = l->next;
while (l)
{
printf(" %d %d", l->coefficient, l->exponent);
l = l->next;
}
printf("\n");
printf("%d %d", m->coefficient, m->exponent);
m = m->next;
while (m)
{
printf(" %d %d", m->coefficient, m->exponent);
m = m->next;
}
return 0;
}
list read()
{
list p = NULL, q = NULL, head = NULL;
int i, a, b, n;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
scanf("%d %d", &a, &b);
p = (list)malloc(sizeof(struct node)); /*新建的节点赋值的时候,要一个一个赋值完*/
if (p)
{
p->coefficient = a;
p->exponent = b;
p->next = NULL;
}
else
exit(1);
if (head == NULL)
{
head = p;
}
else
{
q->next = p;
}
q = p;
}
return head;
}
list multi(list m, list n)
{
list head = NULL, p = NULL, q = NULL, t = NULL;
while (m)
{
t = n;
while (t)
{
p = (list)malloc(sizeof(struct node));
if (p)
{
p->coefficient = m->coefficient * t->coefficient;
p->exponent = m->exponent + t->exponent;
p->next = NULL;
}
else
exit(1);
if (head == NULL)
{
head = p;
}
else
{
q->next = p;
}
q = p;
t = t->next;
}
m = m->next;
}
head = de(head);
head = swap(head);
head = in(head);
return head; /*返回值只能是头节点啊,任何时候都不要用头节点去进行后移操作,切记*/
}
list plus(list m, list n)
{
list head = NULL, p = NULL;
while (m)
{
if (head == NULL)
{
head = m;
}
else
{
p->next = m;
}
p = m;
m = m->next;
}
while (n)
{
p->next = n;
p = n;
n = n->next;
}
head = de(head);
head = swap(head);
head = in(head);
return head;
}
list swap(list m)
{
list h = NULL, t = NULL, f = NULL;
h = m;
t = m;
f = m;
int a, b;
while (h)
{
t = h->next;
while (t)
{
if (t->exponent > h->exponent)
{
a = t->exponent;
t->exponent = h->exponent;
h->exponent = a;
b = t->coefficient;
t->coefficient = h->coefficient;
h->coefficient = b;
}
t = t->next; /*无时无刻都要想到节点后移啊,我又给忘了,烦人*/
}
h = h->next;
} /*排序就是选择排序法*/
return f;
} /*排序函数*/
list in(list m)
{
list p, q, t;
t = m;
p = m;
q = p->next;
while (q)
{
if (p->coefficient == 0)
{
p = p->next;
q = p->next;
}
else
{
if (p->exponent == q->exponent)
{
p->coefficient = p->coefficient + q->coefficient;
p->next = q->next;
free(q);
q = p->next;
}
else
{
p = q;
q = p->next;
}
}
}
return t;
}
list de(list m)
{
list a, b;
a = m;
b = m;
while (b)
{
if (b->coefficient == 0)
{
b->exponent = 0;
}
b = b->next;
}
return a;
}