PTA
7-1(链表) 一元多项式的乘法与加法运算 (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 <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define OK 1
#define Error 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef struct LNode
{
int coef, expn;
struct LNode *next;
}LNode, *LinkList;
Status InitList(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
if(!L)exit(OVERFLOW);
L->next = NULL;
return OK;
}
Status ScanList(LinkList &L)
{
int n;
scanf("%d", &n);
LNode *p, *temp;
temp = L;
while(n--)
{
p = (LinkList)malloc(sizeof(LNode));
if(!p)exit(OVERFLOW);
scanf("%d %d", &p->coef, &p->expn);
temp->next = p;
p->next = NULL;
temp = p;
}
return OK;
}
void AddList(LinkList &La, LinkList &Lb)
{
LNode *p, *q, *m, *n;
p = La->next;
q = Lb->next;
m = La;
while(p && q)
{
if(q->expn > p->expn)
{
Lb->next = q->next;
m->next = q;
q->next = p;
m = q;
q = Lb->next;
}
else if(q->expn < p->expn)
{
p = p->next;
m = m->next;
}
else if(q->expn == p->expn)
{
if(p->coef + q->coef == 0)
{
m->next = p->next;
free(p);
p = m->next;
Lb->next = q->next;
free(q);
q = Lb->next;
}
else
{
p->coef += q->coef;
//删除q
Lb->next = q->next;
free(q);
q = Lb->next;
}
}
}
if(q)
m->next = q;
}
void PrintList(LinkList L)
{
LNode *p = L->next;
if(!p)
printf("0 0");
while(p)
{
if(p->next == NULL)
printf("%d %d", p->coef, p->expn);
else
printf("%d %d ", p->coef, p->expn);
p = p->next;
}
}
LinkList MultiList(LinkList &La, LinkList &Lb)
{
LinkList L0;
InitList(L0);
LNode *p, *q, *l, *temp, *ll;
p = La->next;
q = Lb->next;
l = L0;
int flag = 0;
while(p)
{
if(flag == 0)
{
while(q)
{
temp = (LinkList)malloc(sizeof(LNode));
if(!temp)exit(OVERFLOW);
temp->coef = p->coef * q->coef;
temp->expn = p->expn + q->expn;
l->next = temp;
temp->next = NULL;
l = temp;
q = q->next;
}
}
else
{
LinkList L1;
InitList(L1);
ll = L1;
while(q)
{
temp = (LinkList)malloc(sizeof(LNode));
if(!temp)exit(OVERFLOW);
temp->coef = p->coef * q->coef;
temp->expn = p->expn + q->expn;
ll->next = temp;
temp->next = NULL;
ll = temp;
q = q->next;
}
AddList(L0, L1);
}
p = p->next;
q = Lb->next;
flag = 1;
}
return L0;
}
int main()
{
LinkList La, Lb, Lc;
InitList(La);
InitList(Lb);
ScanList(La);
ScanList(Lb);
Lc = MultiList(La, Lb);
PrintList(Lc);
printf("\n");
AddList(La, Lb);
PrintList(La);
return 0;
}