#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct poly
{
float coef;
int expn;
struct poly *next;
}POLY;
POLY * create(int n);
void Add(POLY *frist,POLY * second);
void print(POLY *frist);
int main(void)
{
int n;
POLY *frist=NULL,*second=NULL;
printf("n:\n");
scanf("%d",&n);
frist=create(n);
print(frist);
scanf("%d",&n);
second=create(n);
print(second);
Add(frist,second);
}
void print(POLY *frist)
{
POLY *p;
for(p=frist->next;p!=NULL;p=p->next)
{
if(p->coef>0)
printf("+%.3fx^%d",p->coef,p->expn);
else
printf("%.3fx^%d",p->coef,p->expn);
}
printf("\n");
}
POLY * create(int n) /*按指数从大到小的输入*/
{
int i;
POLY *p,*L;
L=(POLY *)malloc((sizeof(POLY)));
L->next=NULL;
for(i=0;i<n;i++)
{
p=(POLY *)malloc((sizeof(POLY)));
scanf("%f%d",&p->coef,&p->expn);
p->next=L->next;
L->next=p;
}
return L;
}
void Add(POLY *frist,POLY * second)
{
POLY *p,*q,*pre_p,*pre_q;
p=frist->next;
q=second->next;
pre_p=frist;
pre_q=second;
while(p && q)
{
if(p->expn<q->expn)
{
pre_p=p;
p=p->next;
}
else if(p->expn==q->expn)
{
if(p->coef+q->coef)
{
p->coef+=q->coef;
pre_q->next=q->next; /*1 */
free(q); /*2 */
q=pre_q->next; /*3 */
}
else
{
pre_p->next=p->next;
free(p);
p=pre_p->next;
pre_q->next=q->next; /*1 */
free(q); /*2 */
q=pre_q->next; /*3 */
} /*可以合在一处处理.*/
}
else
{
pre_q->next=q->next;
q->next=p;
pre_p->next=q;
}
}
if(q)
{
pre_p->next=q;
}
free(second);
print(frist);
getch();
}