# 数据结构课程设计一元多项式的相加和相乘

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

typedef struct polynode
{
int coef; //多项式的系数
int exp; //指数
struct polynode *next;
}node;

node *create() //用尾插法建立一元多项式的链表
{
node *h,*r,*s;
int c,e;
h=(node*)malloc(sizeof(node));
r=h;
printf("coef:");
scanf("%d",&c);
printf("exp: ");
scanf("%d",&e);
while(c!=0) //输入系数为0时，多项式的输入结束
{
s=(node*)malloc(sizeof(node));
s->coef=c;
s->exp=e;
r->next=s;
r=s;
printf("coef:");
scanf("%d",&c);
printf("exp: ");
scanf("%d",&e);
}
r->next=NULL;
return(h);
}

void print(node *p) //输出函数，打印出一元多项式
{
while(p->next!=NULL)
{
p=p->next;
printf(" %d*x^%d",p->coef,p->exp);

}
}

{
node *p,*q,*pre,*temp;
int sum;
p=ha->next;
q=hb->next;
pre=ha;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
pre->next=p;
pre=pre->next;
p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
pre->next=p;pre=pre->next;p=p->next;
temp=q;q=q->next;free(temp);
}
else //如果系数和为零，则删除结点p与q，并将指针指向下一个结点
{
temp=p->next;free(p);p=temp;
temp=q->next;free(q);q=temp;
}
}
else
{
pre->next=q;
pre=pre->next;
q=q->next;
}
}
if(p!=NULL) //将多项式A中剩余的结点加入到和多项式中
pre->next=p;
else
pre->next=q;
}

void multipoly(node *ha,node *hb)
{ node *p,*q,*n,*m;
p=ha->next;
n=(node*)malloc(sizeof(node));
n->next=NULL;
while(p!=NULL)
{ m=(node*)malloc(sizeof(node));
for(q=hb->next;q;q=q->next)
{ m->coef=p->coef*q->coef;
m->exp=p->exp+q->exp;
m->next=NULL;
}
p=p->next;
}
printf("多项式的积是:/n");
printf("/n");
}

void main()
{
node *ha,*hb;
printf("请输入多项式ha的系数与指数:/n");
ha=create();
print(ha);
printf("/n");
printf("请输入多项式hb的系数与指数:/n");
hb=create();
print(hb);
printf("/n");
printf("多项式的和是:/n");