/*
2007-3-22
一元多项式的加法
*/
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
typedef struct PolyNode
{
int coef;
int exp;
struct PolyNode *next;
}node;
node *CreatePoly(void)
{
node *h,*tail,*s;
int coef, exp;
h = (node *)malloc(sizeof(node));
if (!h)
{
exit(-1);
}
h->next = NULL;
tail = h;
printf("请输入每一项额系数和指数(中间以逗号隔开):/n");
printf("coef,exp: ");
scanf("%d,%d",&coef,&exp);
while (coef)
{
s = (node *)malloc (sizeof(node));
if (!s)
{
exit(-1);
}
s->coef = coef;
s->exp = exp;
s->next = tail->next;
tail->next = s;
tail = s;
printf("ceof,exp: ");
scanf("%d,%d",&coef,&exp);
}
return h;
}
void PolyAdd(node *polya, node *polyb)
{
node *p, *q, *pre, *temp;
int sum = 0;;
p = polya->next;
q = polyb->next;
pre = polya;
while (p && q)
{
if (p->exp < q->exp)
{
pre->next = p;
pre = p;
p = p->next;
}
else if (p->exp > q->exp)
{
pre->next = q;
pre = q;
q = q->next;
}
else
{
sum = p->coef + q->coef;
if (sum)
{
p->coef = sum;
pre->next = p;
pre = p;
p = p->next;
temp = q->next;
free(q);
q = temp;
}
else
{
temp = p->next;
free(p);
p = temp;
temp = q->next;
free(q);
q = temp;
}
}
}
pre->next = p?p:q;
}
int Prin(node *h)
{
node *p = h->next;
while (p)
{
printf("%d*x^%d ",p->coef, p->exp);
p = p->next;
}
printf("/n");
return 1;
}
int main(void)
{
node *polya, *polyb;
printf("请输入第一个一元多项式的系数和指数(假定以输入系数为0来结束):/n");
polya = CreatePoly();
printf("请输入的第一个一元多项式为:/n");
Prin(polya);
printf("请输入第二个一元多项式的系数和指数(假定以输入系数为0来结束):/n");
polyb = CreatePoly();
printf("请输入的第二个一元多项式为:/n");
Prin(polyb);
printf("这两个一元多项式相加后的结果为:/n");
PolyAdd(polya, polyb);
Prin(polya);
return 1;
}