polynomial 一元多项式加法实现
#include "stdio.h"
#include "malloc.h"
#include "stdlib.h"
typedef struct LNode{
float coef;
int expn;
struct LNode *next;
}Link,*LinkList;
LinkList InitList()
{
Link * head = (LinkList)malloc(sizeof(Link));
head->coef = 0.0;
head->expn = 0;
head->next = NULL;
return head;
}
Link * MakeNode()
{
float inCoef;
int inExpn;
Link * node = (LinkList)malloc(sizeof(Link));
printf("coef : ");
scanf("%f",&inCoef);
printf("expn : ");
scanf("%d",&inExpn);
node->coef = inCoef;
node->expn = inExpn;
return node;
}
LinkList CreatePolyn()
{
int i;
int a;
Link * node = NULL;
Link * p = NULL;
Link * q = NULL;
Link * head = InitList();
printf("input the number of La's items: ");
scanf("%d",&a);
for( i=0; i < a; i++)
{
node = MakeNode();
q = head->next;
p = head;
while( q && node->expn > q->expn )
{
p = q;
q = q->next;
}
if( node->expn == 0)
{
head->coef += node->coef;
}
else if( q == NULL || node->expn < q->expn )
{
p->next = node;
node->next = q;
}
else
{
q->coef += node->coef;
}
}
return head;
}
int Compare( int aExpn, int bExpn)
{
return ( (aExpn > bExpn) ? 1 : ((aExpn == bExpn) ? 0 : -1) );
}
void DelFirst( Link * head, Link * q)
{
q = head->next;
head->next = head->next->next;
}
int ListEmpty( LinkList L)
{
if(L->next==NULL)
return 1;
else
return 0;
}
void Append(LinkList L, Link * q)
{
Link * p = L;
while( p->next )
p = p->next;
p->next = q;
}
void AddPolyn( LinkList La, LinkList Lb)
{
Link * ha = La;
Link * hb = Lb;
Link * qa = ha->next;
Link * qb = hb->next;
ha->coef += hb->coef; //常数项的加法
while(qa && qb)
{
int aExpn, bExpn;
float aCoef,bCoef;
aExpn = qa->expn;
bExpn = qb->expn;
aCoef = qa->coef;
bCoef = qb->coef;
switch( Compare(aExpn, bExpn) )
{
case -1:
{
ha=qa;
qa=qa->next;
break;
}
case 0:
{
float sum = aCoef+bCoef;
if(sum != 0.0)
{
qa->coef = sum;
ha=qa;
}
else
{
DelFirst(ha,qa);
free(qa);
}
DelFirst(hb,qb);
free(qb);
qb = hb->next;
qa = ha->next;
break;
}
case 1:
{
DelFirst(hb,qb);
qb->next = ha->next;
ha->next = qb;
qb= hb->next;
ha= ha->next;
break;
}
}
}
if( !ListEmpty(Lb) )
Append(La,qb);
free(hb);
}
void PrintPolyn(LinkList L)
{
LinkList p= L;
while(p)
{
if(p->coef == 0.0 && p->expn == 0)
{
printf("");
p=p->next;
}
else
{
printf("%1.1f",p->coef);
if(p->expn )
printf("*x^%d",p->expn );
if(p->next && p->next->coef >0)
printf("+");
p=p->next;
}
}
printf("/n");
}
void main()
{
LinkList La = CreatePolyn();
LinkList Lb = CreatePolyn();
AddPolyn( La, Lb );
PrintPolyn( La );
}