学习数据结构,本文记录一下使用链表完成一元多项式的乘法与加法运算的题目:
题目及要求如下
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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<iostream>
using namespace std;
typedef struct node* list;//定义好节点指针
struct node
{
int co;//系数
int ex;//指数
list next = NULL;
};
list Read();
list plustwo(list a, list b);
list mul(list a, list b);
list multep(int c, int e, list a);
void printlist(list l);
int main()
{
list l1 = Read();
list l2 = Read();
list l3 = plustwo(l1, l2);
list l4 = mul(l1, l2);
printlist(l4);
printlist(l3);
return 0;
}
list Read()//定义通过读取构建二项式链表
{
list p;
list L = (list)malloc(sizeof(struct node));
p = L;
int k;
scanf("%d", &k);
for (int i = 0; i < k; i++)
{
list tep = (list)malloc(sizeof(struct node));//新建一个节点
scanf("%d %d", &tep->co, &tep->ex);
tep->next = NULL;
p->next = tep;
p = tep;
}
return L;
}
list plustwo(list a, list b)//定义两个多项式链表的加法运算
{
list pa, pb, pl;
list L = (list)malloc(sizeof(struct node));
pa = a->next;
pb = b->next;
pl = L;
while (pa&&pb)
{
list tep = (list)malloc(sizeof(struct node));
if (pa->ex == pb->ex)
{
tep->ex = pa->ex;
tep->co = pa->co + pb->co;
tep->next = NULL;
pa = pa->next;
pb = pb->next;
if (tep->co == 0)continue;
}
else
{
if (pa->ex > pb->ex)
{
tep->ex = pa->ex;
tep->co = pa->co;
tep->next = NULL;
pa = pa->next;
}
else
{
tep->ex = pb->ex;
tep->co = pb->co;
tep->next = NULL;
pb = pb->next;
}
}
pl->next = tep;
pl = tep;
}
pl->next = pa ? pa : pb;
return L;
}
void printlist(list L)//定义打印多项式的函数
{
if (!L->next)
{
printf("0 0\n");
return;
}
int flag = 0;
list pl = L;
while (pl->next)
{
pl = pl->next;
if (flag)
printf(" %d %d", pl->co, pl->ex);
else
{
printf("%d %d", pl->co, pl->ex);
flag = 1;
}
}
printf("\n");
return;
}
list multep(int c, int e, list a)//定义一个多项式与一个单项式的乘法运算
{
list L = (list)malloc(sizeof(struct node));
list pl, pa;
pl = L;
pa = a->next;
while (pa)
{
list tep = (list)malloc(sizeof(struct node));
tep->co = pa->co*c;
tep->ex = pa->ex + e;
tep->next = NULL;
pl->next = tep;
pl = tep;
pa = pa->next;
}
return L;
}
list mul(list a, list b)//调用上一个函数完成加法到乘法的转化
{
list pa, pb, pl;
list L = (list)malloc(sizeof(struct node));
pa = a->next;
pb = b->next;
pl = L;
pl->next = NULL;
while (pa)
{
list tep = multep(pa->co, pa->ex, b);
pl = plustwo(pl, tep);
pa = pa->next;
}
return pl;
}