include
include
//int *p 指向 int 类型
// 前面加上 typedef 可以让 POINTER 指向 struct POLYNODE 类型
typedef struct POLYNODE *POINTER;
// 定义一个 struct 类型
struct POLYNODE{
int coef;
int expon;
POINTER link;
};
POINTER ReadPoly();
void Attach(int c, int e, POINTER *pRear);
POINTER Add(POINTER P1, POINTER P2);
POINTER Mult(POINTER P1, POINTER P2);
void PrintPoly(POINTER P);
int main(){
POINTER P1,P2,PM,PA;
P1 =ReadPoly();
P2 =ReadPoly();
PM=Mult(P1,P2);
PrintPoly(PM);
PA =Add(P1,P2);
PrintPoly(PA);
return 0;
}
// 构造一个头结点,不断向后添加
POINTER ReadPoly(){
POINTER P,Rear,t;
int c,e,N;
scanf("%d",&N);
P = (POINTER)malloc(sizeof(struct POLYNODE)); //?????????
P->link = NULL;
Rear = P;
while(N--){
scanf("%d %d",&c,&e);
Attach(c,e,&Rear); //??????????????β??
}
t = P; P = P->link; free(t); //???????????????
return P;
}
// 在尾指针后面不断添加
//attach 方法的使用必须保证有一个空的头结点
void Attach(int c, int e, POINTER pRear){
POINTER P;
P = (POINTER)malloc(sizeof(struct POLYNODE));
P->coef = c;
P->expon = e;
P->link = NULL;
(pRear)->link = P;
pRear = P;
}
// 构造一个新链,不断
POINTER Add(POINTER P1,POINTER P2){
POINTER front,temp,rear;
front = (POINTER)malloc(sizeof(struct POLYNODE));
rear = front;
while(P1&&P2){
if(P1->expon>P2->expon){
Attach(P1->coef,P1->expon,&rear);
P1=P1->link;
}else if(P1->exponexpon){ t2->coef,t1->expon+t2->expon,&rear);
Attach(P2->coef,P2->expon,&rear);
P2=P2->link;
}else {
if(P2->coef+P1->coef){
Attach(P2->coef+P1->coef,P2->expon,&rear);
}
P1=P1->link;
P2=P2->link;
}
}
while(P1){
Attach(P1->coef,P1->expon,&rear);
P1=P1->link;
}
while(P2){
Attach(P2->coef,P2->expon,&rear);
P2=P2->link;
}
rear->link=NULL;
temp = front;
front = front->link;
free(temp);
return front;
}
POINTER Mult(POINTER P1,POINTER P2){
POINTER t1,t2,P,rear,temp;
int c,e;
if(!P1||!P2) return NULL;
t1=P1;t2=P2;
P = (POINTER)malloc(sizeof(struct POLYNODE));P->link=NULL;
rear = P;
while(t2){
// 构造新链,先把 t1 的第一项依次与 t2 作用
Attach(t1->coef
t2=t2->link;
}
t1=t1->link;
while(t1){
t2=P2;rear=P;
while(t2){
e=t1->expon+t2->expon;
//while 循环时,使用 rear->link 方便
while(rear->link&&rear->link->expon>e){
rear=rear->link;
}
if(rear->link&&rear->link->expon==e){
if (rear->link->coef+c) {
rear->link->coef += c;
}
else {
rear->link = rear->link->link;
}
}else{
temp = (POINTER)malloc(sizeof(struct POLYNODE));
temp->coef = c; temp->expon = e;
temp->link = rear->link;
rear->link = temp; rear = rear->link;
}
t2=t2->link;
}
t1=t1->link;
}
temp = P; P = P->link; free(temp);
return P;
}
void PrintPoly(POINTER 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");
}