目录
求两个一元多项式的和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分1行,分别以指数递降方式输出和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
样例1" name="输入样例1">输入样例1:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例1:
5 20 -4 4 -5 2 9 1 -2 0
#include<bits/stdc++.h>
using namespace std;
typedef struct PolyNode *Polynomial;
struct PolyNode{
int coef;
int expon;
Polynomial link;
};
void Attach(int c,int e,Polynomial *pRear)
{
Polynomial temp;
temp=(Polynomial)malloc(sizeof(struct PolyNode));
temp->coef=c;/*对新节点赋值*/
temp->expon=e;
temp->link=(*pRear)->link;
(*pRear)->link=temp;
(*pRear)=temp;/*修改pRear值*/
}
Polynomial ReadPoly()
{
Polynomial P,Rear,first;
int N;
int c,e;
P=(Polynomial)malloc(sizeof(struct PolyNode));/*链表头空结点*/
P->link=NULL;
Rear=P;
scanf("%d",&N);
while(N--){
scanf("%d %d",&c,&e);
Attach(c,e,&Rear);/*将当前项插入多项式尾部*/
}
first=P;P=P->link;free(first);/*删除临时生成的头结点*/
return P;
}
Polynomial Add(Polynomial P1,Polynomial P2)
{
Polynomial t,t1,t2,P;
t1=P1;t2=P2;
P=(Polynomial)malloc(sizeof(struct PolyNode)); P->link=NULL;
t=P;
while(t1&&t2){
if(t1->expon>t2->expon){
Attach(t1->coef,t1->expon,&t);
t1=t1->link;
}
else if(t1->expon<t2->expon)
{
Attach(t2->coef,t2->expon,&t);
t2=t2->link;
}else
{
if(!(t1->coef+t2->coef)==0)
{
Attach(t1->coef+t2->coef,t1->expon,&t);
t1=t1->link;
t2=t2->link;
}else{
t1=t1->link;
t2=t2->link;
}
}
}
for(;t1;t1=t1->link)
{
Attach(t1->coef,t1->expon,&t);
}
for(;t2;t2=t2->link)
{
Attach(t2->coef,t2->expon,&t);
}
t=P;
P=P->link;
free(t);
return P;
}
void PrintPoly(Polynomial P)
{
/*输出多项式*/
int flag=0;
if(!P){
printf("0 0\n"); return;
}
while(P){
if(!flag)
flag=1;
else
printf(" ");
printf("%d %d",P->coef,P->expon);
P=P->link;
}
printf("\n");
}
int main()
{
Polynomial P1,P2,PP,PS;
P1=ReadPoly();
P2=ReadPoly();
// PrintPoly(PP);
PS=Add(P1,P2);
PrintPoly(PS);
return 0;
}