设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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 <stdio.h>
#include <stdlib.h>
typedef struct _Node
{
int k;
int e;
struct _Node * next;
}Node;
typedef Node * List;
void printList(List l)
{
if (l->next == NULL)
{
printf("0 0");
}
else
{
while(l->next != NULL)
{
printf("%d %d", l->next->k, l->next->e);
l = l->next;
if (l ->next != NULL)
printf(" ");
}
}
}
List newNode(int k, int e)
{
List l = (List)malloc(sizeof(Node));
l->k = k;
l->e = e;
l->next = NULL;
return l;
}
void insertList(List l, int k, int e)
{
while(l->next != NULL)
{
if (l->next->e == e)
{
l->next->k += k;
// if the sum = 0, delete this item
if (l->next->k == 0)
{
List temp = l->next;
l->next = temp->next;
free(temp);
temp = NULL;
}
return;
}
else if (l->next->e < e)
{
List temp = newNode(k,e);
temp->next = l->next;
l->next = temp;
return;
}
l = l->next;
}
List temp = newNode(k,e);
l->next = temp;
}
int main(void)
{
List l1, l2, lp, ls, t;
l1 = newNode(0,0);
l2 = newNode(0,0);
lp = newNode(0,0);
ls = newNode(0,0);
int n;
// input first polynomial
scanf("%d", &n);
t = l1;
for (int i=0;i<n;i++)
{
int k, e;
scanf("%d %d", &k, &e);
t->next = newNode(k, e);
t = t->next;
}
// input second polynomial
scanf("%d", &n);
t = l2;
for (int i=0;i<n;i++)
{
int k, e;
scanf("%d %d", &k, &e);
t->next = newNode(k, e);
t = t->next;
}
// calculate the product
List l1Temp = l1;
List l2Temp = l2;
while(l1->next != NULL)
{
l2 = l2Temp;
while(l2->next != NULL)
{
int e = l1->next->e + l2->next->e;
int k = l1->next->k * l2->next->k;
insertList(lp, k ,e);
l2 = l2->next;
}
l1 = l1->next;
}
printList(lp);
printf("\n");
// calculate the sum
l1 = l1Temp;
l2 = l2Temp;
while(l1->next != NULL)
{
int e = l1->next->e;
int k = l1->next->k;
insertList(ls, k ,e);
l1 = l1->next;
}
while(l2->next != NULL)
{
int e = l2->next->e;
int k = l2->next->k;
insertList(ls, k ,e);
l2 = l2->next;
}
printList(ls);
}
一元多项式运算实现
本文介绍了一种使用链表结构实现一元多项式乘法和加法的方法。通过输入两个多项式的非零项,程序能够正确计算并输出它们的乘积与和,采用递降指数形式展示结果。该算法首先读取两个多项式,然后逐项计算乘积和和,最后将结果以指定格式打印。
1127

被折叠的 条评论
为什么被折叠?



