s=t; } }
if (q) p=q;//p恒指向余下的项 while (p) {
t=new Node; t->coef=p->coef; t->exp=p->exp; s->next=t; s=t; p=p->next; }
s->next=0; //链表尾标记 s=temp.head; temp.head=s->next;
delete s; //删除多余的头结点 return temp; }
Polynominal operator -(Polynominal a,Polynominal b)//重载-运算符 {
Polynominal temp; Node *p,*q,*s=0,*t;
//在此处添加代码,完成此函数(模仿上述重载\的函数) double x;
s=new Node;temp.head=s;//先增加一个头结点 p=a.head; q=b.head; while (p && q) {
if (p->exp==q->exp) {
x=p->coef-q->coef; if (x!=0.0)
- 8 -
{
t=new Node; t->exp=p->exp; t->coef=x; s->next=t; s=t; } p=p->next; q=q->next; } else {
t=new Node; if(p->exp>q->exp) {
t->coef=p->coef; t->exp=p->exp; p=p->next; } else {
t->coef=-q->coef; t->exp=q->exp; q=q->next; }
s->next=t; s=t; } }
if (q) p=q;//p恒指向余下的项 while (p) {
t=new Node; t->coef=p->coef;
- 9 -
t->exp=p->exp; s->next=t; s=t; p=p->next; }
s->next=0; //链表尾标记 s=temp.head; temp.head=s->next;
delete s; //删除多余的头结点 return temp; }
Polynominal operator *(Polynominal a,Polynominal b)//重载*运算符 {
Polynominal temp; Node *p,*q,*s; int e;double c; p=a.head; while (p) {
q=b.head; while (q) {
c=p->coef*q->coef; e=p->exp+q->exp;
s=temp.get(e);//查temp中有无指数为e的项 if (s)//temp中无指数为e的项 s->coef+=c;
else//temp中无指数为e的项 temp.set(c,e); q=q->next; } p=p->next; }
return temp;
- 10 -
}
ostream& operator<<(ostream& os, const Polynominal& a) {
a.Print(os); return os; }
Polynominal& Polynominal::operator =(Polynominal a)//重载=运算符 {
Node *s,*p; if (head)
{ //若原多项式存在,先撤消它 p=head; while (p) {
s=p->next; delete p; p=s; } } Copy(a); return *this; }
void Polynominal::Print(ostream& os) const//显示多项式 {
Node* p;int e; if (head) {
e=head->exp;
os<<\ if (e>1) os<<\
- 11 -
if (e==1) os<<\ } else {
os << \ return; } p=head->next; while (p) {
e=p->exp;
if (p->coef!=0.0)//系数非零 {
if (p->coef>0.0) os<<'+'< 通过类的成员函数实现对多项式的运算,构造和析构函数主要是实现初始化以及销毁,其它函数则主要是实现功能。 4.3 主函数设计 //主函数 int main() { int e1[MAXSIZE],e2[MAXSIZE],size2,size1,i; double c1[MAXSIZE],c2[MAXSIZE]; cout<<\多项式计算器------------\ - 12 -