#include<iostream>
using namespace std;
typedef struct Polynode{
int coef;
int exp;
struct Polynode *next;
}Polynode, *Polylist;
Polylist create()
{
Polynode *s, *rear, *head;
head = (Polynode*)malloc(sizeof(Polynode));
rear = head;
int a, b;
cin >> a >> b;
while(a != 0)
{
s = (Polynode*)malloc(sizeof(Polynode));
s->coef = a;
s->exp = b;
rear->next = s;
rear = s;
cin >> a >>b;
}
rear->next = NULL;
return (head);
}
void show(Polylist poly)
{
Polynode *p;
int c;
int e;
p = poly->next;
while(p->next != NULL)//避免最后一项也出现加号
{
c=p->coef;
e=p->exp;
cout << c << "X^" << e << "+";
p=p->next;
}
c=p->coef;
e=p->exp;
printf("%dX^%d",c,e);
}
Polylist polyadd(Polylist pa, Polylist pb)
{
Polynode *p, *q, *tail, *head, *s;
int sum;
head = (Polynode*)malloc(sizeof(Polynode));
p = pa->next;
q = pb->next;
tail = head;
while(p != NULL&&q != NULL)
{
if(p->exp < q->exp)
{
tail->next = p;
tail = p;
p = p->next;
}
else if(p->exp > q->exp)
{
tail->next = q;
tail= q;
q = q->next;
}
else
{
sum = p->coef + q->coef;
if(sum)
{
p->coef = sum;
tail->next = p;
tail = p;
p = p->next;
s = q;
q = q->next;
free(s);
}
else
{
s = p;
p = p-> next;
free(s);
s = q;
q = q->next;
free(s);
}
}
}
if(p!=NULL)
tail->next= p;
else tail->next = q;
return (head);
}
int main()
{
Polylist pa, pb;
cout << "请按升幂输入多项式A,以系数为0结束:\n";
pa = create();
cout << "你输入的多项式为:\n";
show(pa);
cout << "\n";
cout << "请按升幂输入多项式B,以系数为0结束:\n";
pb = create();
cout <<"你输入的多项式为:\n";
show(pb);
cout << "\n";
cout << "结果多项式为:\n";
show(polyadd(pa, pb));
return 0;
}
一元多项式的加法
最新推荐文章于 2023-10-01 18:03:31 发布