02-线性结构2 一元多项式的乘法与加法运算 (20分)
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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
#include<cstdio>
#include<cstdlib>
typedef struct node {
int coef;
int exp;
struct node *next;
}Node;
Node *create_node() {
Node *node = (Node*)malloc(sizeof(Node));
node->coef = node->exp = 0;
node->next = NULL;
return node;
}
void copy_list1_to_list2(Node *list1, Node *list2) {
while (list1) {
Node *node = create_node();
node->coef = list1->coef;
node->exp = list1->exp;
list2->next = node;
list2 = list2->next;
list1 = list1->next;
}
}
void read(Node *list) {
int n;
scanf("%d", &n);
while (n--) {
Node *node = create_node();
scanf("%d%d", &node->coef, &node->exp);
list->next = node;
list = list->next;
}
}
void release(Node *list) {
Node *pre = list, *cur = list->next;
while (cur) {
free(pre);
pre = cur;
cur = cur->next;
}
free(pre);
}
Node* polynomial_add(Node *l1, Node *l2) {
Node *l = create_node();
l1 = l1->next, l2 = l2->next;
Node *head = l;
while (l1 && l2) {
if (l1->exp > l2->exp) {
Node *node = create_node();
node->coef = l1->coef;
node->exp = l1->exp;
l->next = node;
l1 = l1->next;
l = l->next;
}
else if (l1->exp < l2->exp) {
Node *node = create_node();
node->coef = l2->coef;
node->exp = l2->exp;
l->next = node;
l2 = l2->next;
l = l->next;
}
else {
int coef_sum = l1->coef + l2->coef;
if (coef_sum == 0) {
l1 = l1->next;
l2 = l2->next;
}
else {
Node *node = create_node();
node->coef = coef_sum;
node->exp = l1->exp;
l1 = l1->next;
l2 = l2->next;
l->next = node;
l = l->next;
}
}
};
if (l1) copy_list1_to_list2(l1, l);
if (l2) copy_list1_to_list2(l2, l);
return head;
}
Node *polynomial_multi(Node *l1, Node *l2) {
Node *res = create_node();
l1 = l1->next;
l2 = l2->next;
while (l1) {
Node *tmp = create_node();
Node *head = tmp;
int coef = l1->coef, exp = l1->exp;
copy_list1_to_list2(l2, tmp);
tmp = tmp->next;
while (tmp) {
tmp->coef *= coef;
tmp->exp += exp;
tmp = tmp->next;
}
Node *res_new = polynomial_add(head, res);
release(res);
release(head);
res = res_new;
l1 = l1->next;
}
return res;
}
void print(Node *node) {
node = node->next;
if (!node) {
printf("0 0\n");
return;
}
int flag = 1;
while (node) {
if (flag) {
printf("%d %d", node->coef, node->exp);
flag = 0;
}
else
printf(" %d %d", node->coef, node->exp);
node = node->next;
}
putchar(10);
}
int main() {
//freopen("input.txt", "r", stdin);
Node *l1 = create_node(), *l2 = create_node();
read(l1);
read(l2);
Node *l_add = polynomial_add(l1, l2);
Node *l_mul = polynomial_multi(l1, l2);
print(l_mul);
print(l_add);
release(l1);
release(l2);
release(l_add);
release(l_mul);
return 0;
}