# [PTA刷题]一元多项式的乘法与加法运算

221人阅读 评论(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 expo;
Polynomial next;
};

Polynomial add(Polynomial P1, Polynomial P2);
Polynomial multi(Polynomial P1, Polynomial P2);
void print(Polynomial P);
void attach(int coef, int expo, Polynomial *rear);

int main(){
Polynomial P4=multi(P1, P2);
print(P4);
print(P3);
return 0;
}

{
Polynomial P = (Polynomial)malloc(sizeof(struct PolyNode));
P->next=NULL;
Polynomial rear,temp;
rear=P;
int num, pcoef, pexpo;
scanf("%d", &num);

while (num) {
scanf("%d %d", &pcoef, &pexpo);
attach(pcoef,pexpo,&rear);
num--;
}
temp=P; P=P->next; free(temp);
return P;

}

void attach(int coef, int expo, Polynomial *rear)
{
Polynomial temp = (Polynomial)malloc(sizeof(struct PolyNode));
temp->next=NULL;
temp->coef=coef;
temp->expo=expo;
(*rear)->next=temp;
*rear=temp;
}

void print(Polynomial P)
{
if(!P){
printf("0 0\n"); return;
}
while (P) {
if(P->next){
printf("%d %d ",P->coef,P->expo);
}
else
printf("%d %d",P->coef,P->expo);
P=P->next;
}
printf("\n");
}

Polynomial add(Polynomial P1, Polynomial P2)
{
Polynomial P,rear,temp2,t1,t2;
P=(Polynomial)malloc(sizeof(struct PolyNode));
P->next=NULL;
rear=P;
t1=P1;t2=P2;

while (t1 && t2) {
if(t1->expo > t2->expo){ //看下面的注释
attach(t1->coef, t1->expo, &rear);
t1=t1->next;
}
else if(t1->expo < t2->expo){
attach(t2->coef, t2->expo, &rear);
t2=t2->next;
}
else{
int tempcoef=t1->coef + t2->coef;
if(tempcoef){
attach(tempcoef, t1->expo, &rear);
}
t1=t1->next;
t2=t2->next;
}
}
while(t1){
attach(t1->coef, t1->expo, &rear);
t1=t1->next;
}

while(t2){
attach(t2->coef, t2->expo, &rear);
t2=t2->next;
}

temp2=P;
P=P->next; free(temp2);

return P;
}

Polynomial multi(Polynomial P1, Polynomial P2)
{
Polynomial P,rear,t1,t2,t;
int c,e;
if(!P1 || !P2) return NULL;

P=(Polynomial)malloc(sizeof(struct PolyNode));
P->next=NULL;
rear=P;
t1=P1;t2=P2;

while(t2){
attach(t1->coef*t2->coef, t1->expo+t2->expo, &rear);

t2=t2->next;
}

t1=t1->next;
while(t1){
t2=P2;rear=P;
while(t2){
c=t1->coef*t2->coef;
e=t1->expo+t2->expo;

while (rear->next && rear->next->expo>e) {
rear=rear->next;
}
if(rear->next && rear->next->expo ==e){
if(rear->next->coef+c){
rear->next->coef+=c;
}
else{
t=rear->next;
rear->next=t->next;
free(t);
}
}
else{
t=(Polynomial)malloc(sizeof(struct PolyNode));
t->coef=c;t->expo=e;
t->next=rear->next;
rear->next=t;
rear=rear->next;
}

t2=t2->next;
}
t1=t1->next;
}
t2=P; P=P->next; free(t2);

return P;
}

rear->next = t1; //!!!

t1 = t1->next;

rear = rear->next;

0
0

个人资料
• 访问：9231次
• 积分：695
• 等级：
• 排名：千里之外
• 原创：63篇
• 转载：8篇
• 译文：0篇
• 评论：0条