#include<stdio.h>
#include<stdlib.h>
//多项式相加
struct poly
{
int zhishu;
float xishu;
};//定义结构的数据部分
typedef struct poly TypeDate;//将 结构体的数据部分 取名为 TypeDate
typedef struct node
{
TypeDate date;
struct node *next;
}Node; // 定义 结构体 取名为 Node
void add(Node *d,int z,float x);//链表的增加 函数
void Print(Node *p); //链表的输出函数
void Sum(Node *sum,Node*p,Node *q); //多项式相加函数
void reset(Node *pList); //链表的消除
int main()
{
int t=1;
printf("格式:\n系数空格指数(输入 0 0 结束)\n输入多项式 1\n");
Node p;
p.next=NULL;
do//多项式一输入
{
int z;
float x;
scanf("%d %f",&z,&x);
t=z;
add(&p,z,x);
}while(t!=0);
printf("输入多项式 2\n");
Node q;
q.next=NULL;
do//多项式二输入
{
int z;
float x;
scanf("%d %f",&z,&x);
t=z;
add(&q,z,x);
}while(t!=0);
Node sum;//创建链表三 用于保存多项式一、二相加
sum.next=NULL;
Sum(&sum,&p,&q);//多项式相加函数
printf("多项式一:");Print(&p);
printf("多项式二:");Print(&q);
printf("多项式一与多项式二和:");Print(&sum);
reset(&p);
reset(&q);
reset(&sum);
return 0;
}
void add(Node *d,int z,float x)//链表的增加 函数
{
if(z==0) return ;
Node *p;
p=(Node*)malloc(sizeof(Node));
while(1)
{
if(d->next==NULL)
{
d->date.xishu=x;
d->date.zhishu=z;
p->next=NULL;
d->next=p;
break;
}
else
{
d=d->next;
}
}
}
void Print(Node *p) //链表的输出函数
{
int flog=0;
while(p->next)
{
if(flog==1)
{
printf(" + ");
}
else{
printf("f(x)=");
}
flog=1;
printf("%0.0fX^%d",p->date.xishu,p->date.zhishu);
p=p->next;
}
printf("\n\n");
}
void Sum(Node *sum,Node*p,Node *q) //多项式相加函数
{
while(p->next!=NULL||q->next!=NULL)
{
while(p->next!=NULL)
{
add(sum,p->date.zhishu,p->date.xishu);
p=p->next;
}
while(q->next!=NULL)
{
Node *s;
s=(Node*)malloc(sizeof(Node));
s=sum;
while(s->next!=NULL)
{
if(q->date.zhishu==s->date.zhishu)
{
s->date.xishu=q->date.xishu+s->date.xishu;
break;
}
else
{
s=s->next;
if(s->next==NULL)
{
add(s,q->date.zhishu,q->date.xishu);
break;
}
}
}
q=q->next;
}
}
}
void reset(Node *pList) //链表的消除
{
Node *p;
Node *q;
for(p=pList->next;p;p=q)
{
q=p->next;
free(p);
}
}