设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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 PolyNode* Polynomial;
//多项式结构
struct PolyNode
{
int coef; //系数
int index; //指数
Polynomial p; //下一个结点
};
Polynomial ReadPoly();
void Attach(int c, int e, Polynomial* pRear);
Polynomial Add(Polynomial P1, Polynomial P2);
Polynomial Mult(Polynomial P1, Polynomial P2);
void PrintPoly(Polynomial P);
int Compare(int a, int b);
int main()
{
Polynomial P1, P2, PP, PS;
P1 = ReadPoly();
P2 = ReadPoly();
PP = Mult(P1, P2);
PrintPoly(PP);
PS = Add(P1, P2);
PrintPoly(PS);
return 0;
}
//读入多项式
Polynomial ReadPoly()
{
Polynomial f, rear, t;
int c, e, n;
scanf("%d", &n);
f = (Polynomial)malloc(sizeof(Polynomial));
f->p = NULL;
rear = f;
while (n--)
{
scanf("%d %d", &c, &e);
Attach(c, e, &rear);
}
t = f;
f = f->p;
free(t);
return f;
}
//添加结点
void Attach(int c, int e, Polynomial* rear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->coef = c;
P->index = e;
P->p = NULL;
(*rear)->p = P;
*rear = P;
}
//比较两数大小
int Compare(int a, int b)
{
if (a > b) return 1;
else if (a < b) return -1;
else return 0;
}
// 多项式相加
Polynomial Add(Polynomial P1, Polynomial P2)
{
Polynomial P, Rear, t, t1, t2;
t1 = P1; t2 = P2;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->p = NULL;
Rear = P;
while (t1 && t2)
{
switch (Compare(t1->index, t2->index))
{
case 1:
Attach(t1->coef, t1->index, &Rear);
t1 = t1->p;
break;
case -1:
Attach(t2->coef, t2->index, &Rear);
t2 = t2->p;
break;
case 0:
if (t1->coef + t2->coef) Attach(t1->coef + t2->coef, t1->index, &Rear);
t1 = t1->p;
t2 = t2->p;
break;
}
}
for (; t1; t1 = t1->p)
Attach(t1->coef, t1->index, &Rear);
for (; t2; t2 = t2->p)
Attach(t2->coef, t2->index, &Rear);
Rear->p = NULL;
t = P;
P = P->p;
free(t);
return P;
}
// 多项式相乘
Polynomial Mult(Polynomial P1, Polynomial P2)
{
Polynomial P, Rear, t1, t2, t;
int c, e;
if (!P1 || !P2) return NULL;
t1 = P1;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->p = NULL;
while (t1)
{
t2 = P2; Rear = P;
while (t2)
{
e = t1->index + t2->index;
c = t1->coef * t2->coef;
while (Rear->p!=NULL && Rear->p->index > e)
Rear = Rear->p;
if (Rear->p && Rear->p->index == e)
{
if (Rear->p->coef + c!=0)
Rear->p->coef += c;
else {
Rear->p = Rear->p->p;
}
}
else
{
t = (Polynomial)malloc(sizeof(struct PolyNode));
t->coef = c;
t->index = e;
t->p = Rear->p;
Rear->p = t;
Rear = t;
}
t2 = t2->p;
}
t1 = t1->p;
}
P = P->p;
free(t2);
free(t1);
return P;
}
//多项式输出
void PrintPoly(Polynomial P)
{
int flag = 0;
if (!P)
{
printf("0 0\n");
return;
}
while (P)
{
if (flag==0) flag = 1;
else printf(" ");
printf("%d %d", P->coef, P->index);
P = P->p;
}
printf("\n");
}