#include <stdio.h>
#include <stdlib.h>
struct Node{
int xs;
int zs;
struct Node* link;
};
typedef struct Node* Ptr;
Ptr Readp();
void Attach(int x,int z,Ptr* q);
Ptr Add(Ptr p1,Ptr p2);
Ptr Muti(Ptr p1,Ptr p2);
int Compare(int a,int b);
void printP(Ptr p);
int main()
{
Ptr p1,p2,padd,pmuti;
p1 = Readp();
p2 = Readp();
padd = Add(p1,p2);
pmuti = Muti(p1,p2);
printP(pmuti);
printP(padd);
return 0;
}
Ptr Readp()
{
Ptr p,tail,temp;
int n,x,z;//分别表示项的个数,每项系数,指数
p = (Ptr)malloc(sizeof(struct Node));
p->link = NULL;
tail = p;
scanf("%d",&n);
while(n--){
scanf("%d %d",&x,&z);
Attach(x,z,&tail);
}
temp = p; p = p->link; free(temp);//删除空结点
return p;
}
void Attach(int x,int z,Ptr *ptail)//新节点生成并链接的函数 ,传入的是当前尾结点的指针的指针
{
Ptr q;
q = (Ptr)malloc(sizeof(struct Node));//申请空结点,以链接后面项的结点
q->xs = x;
q->zs = z;
q->link = NULL;
(*ptail)->link = q;
*ptail = q;
}
Ptr Add(Ptr p1,Ptr p2)
{
int sum = 0;
Ptr padd,tail,temp;
padd = (Ptr)malloc(sizeof(struct Node));
tail = padd;
while(p1&&p2){
switch(Compare(p1->zs,p2->zs)){
case 1:
Attach(p1->xs,p1->zs,&tail);
p1 = p1->link;
break;
case -1:
Attach(p2->xs,p2->zs,&tail);
p2 = p2->link;
break;
case 0:
sum = p1->xs + p2->xs;
if(sum!=0)
Attach(sum,p1->zs,&tail);
p1 = p1->link;
p2 = p2->link;
sum = 0;
break;
}
}
for(; p1; p1= p1->link)
Attach(p1->xs,p1->zs,&tail);
for(; p2; p2= p2->link)
Attach(p2->xs,p2->zs,&tail);
tail->link = NULL;
temp = padd;
padd = padd->link;
free(temp);
return padd;
}
Ptr Muti(Ptr p1,Ptr p2)
{
Ptr t1,t2,P,tail,t;
if(!p1||!p2) return NULL;
int c = 0;
int e = 0;
t1 = p1;
t2 = p2;
P = (Ptr)malloc(sizeof(struct Node));
P->link = NULL;
tail = P;
while(t2){
Attach(t1->xs*t2->xs,t1->zs+t2->zs,&tail);
t2 = t2->link;
}
t1 = t1->link;
while(t1){
t2 = p2;
tail = P;
while(t2){
c = t1->xs*t2->xs;
e = t1->zs+t2->zs;
while(tail->link&&tail->link->zs>e){
tail = tail->link;
}
if(tail->link&&tail->link->zs == e){
if(tail->link->xs+c){
tail->link->xs+=c;
}
else {
t = tail->link;
tail->link = t->link;
free(t);
}
}
else {
t = (Ptr)malloc(sizeof(struct Node));
t->xs = c;
t->zs = e;
t->link = tail->link;
tail->link = t;
tail = tail->link;
}
t2 = t2->link;
}
t1 = t1->link;
}
t = P;
P = P->link;
free(t);
return P;
}
int Compare(int a,int b)
{
if(a>b)
return 1;
else if(a<b)
return -1;
else
return 0;
}
void printP(Ptr p)
{
int flag = 0;//用于两组数据间插入空格
if(!p){
printf("0 0\n");
return;
}
while(p){
if(!flag)
flag = 1;
else
printf(" ");
printf("%d %d",p->xs,p->zs);
p = p->link;
}
printf("\n");
}
难,跟着何老师一段一段打的,略有差异
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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