一元多项式的乘法与加法运算
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
在这里插入代码片
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct PolyNode *polynode;
struct PolyNode{
ElementType coef;
ElementType expon;
polynode Next;
};
typedef polynode List;
List readpoly();
List addpoly(List head1,List head2);
List multpoly(List head1,List head2);
void freelist(List head);
void printpoly(List head);
int main(){
List p1,p2;
p1 = readpoly();
p2 = readpoly();
List p3 = multpoly(p1,p2);
List p4 = addpoly(p1,p2);
printpoly(p3);
printf("\n");
printpoly(p4);
return 0;
}
List readpoly(){ //用带头节点的链表读入数据
ElementType N,c,e;
scanf("%d",&N);
List head = (List)malloc(sizeof(struct PolyNode));
head->Next = NULL;
List temp = head;
while(N){
List p = (List)malloc(sizeof(struct PolyNode));
p->Next = NULL;
scanf("%d %d",&c,&e);
p->coef = c;
p->expon = e;
temp->Next = p;
temp = p;
N--;
}
return head;
}
List addpoly(List head1,List head2){
List temp1 = head1;
List temp2 = head2;
List head = (List)malloc(sizeof(struct PolyNode));
head->Next = NULL;
List temp = head;
while(temp1->Next&&temp2->Next){ //为什么用temp1->next,方便将后面的数据直接连接到链表上
List p = (List)malloc(sizeof(struct PolyNode));
p->Next = NULL;
if(temp1->Next->expon==temp2->Next->expon){
if(temp1->Next->coef + temp2->Next->coef == 0){
temp1 = temp1->Next;
temp2 = temp2->Next;
free(p); //若系数相加为零,则释放该节点
continue; //结束此次循环
}
else{
p->coef = temp1->Next->coef + temp2->Next->coef;
p->expon = temp1->Next->expon;
temp1 = temp1->Next;
temp2 = temp2->Next;
}
}
else if(temp1->Next->expon > temp2->Next->expon){
p->coef = temp1->Next->coef;
p->expon = temp1->Next->expon;
temp1 = temp1->Next;
}
else{
p->coef = temp2->Next->coef;
p->expon = temp2->Next->expon;
temp2 = temp2->Next;
}
temp->Next = p;
temp = p;
}
if(temp1->Next==NULL){
temp->Next = temp2->Next;
temp2->Next = NULL; //必须为NULL,否则freelist的时候会把返回的链表后面也释放掉
}
else{
temp->Next = temp1->Next;
temp1->Next = NULL;
}
return head;
}
List multpoly(List head1,List head2){ //先一项相乘,在相加可进行排序
List temp1 = head1->Next;
List temp2 = head2->Next;
List phead = (List)malloc(sizeof(struct PolyNode));
phead->Next = NULL;
while(temp1){
temp2 = head2->Next;
List head = (List)malloc(sizeof(struct PolyNode));
head->Next = NULL;
List temp = head;
while(temp2){
List p = (List)malloc(sizeof(struct PolyNode));
p->Next= NULL;
p->coef = temp1->coef * temp2->coef;
p->expon = temp1->expon + temp2->expon;
temp->Next = p;
temp = p;
temp2 = temp2->Next;
}
temp1 = temp1->Next;
phead = addpoly(phead,head);
freelist(head); //及时释放空间
}
return phead;
}
void freelist(List head){
while(head){
List temp = head;
head = temp->Next;
free(temp);
}
}
void printpoly(List head){
if(head->Next==NULL){
printf("%d %d",0,0);
}
else{
head = head->Next;
while(head->Next){
printf("%d %d ",head->coef,head->expon);
head = head->Next;
}
printf("%d %d",head->coef,head->expon);
}
}