给出一元多项式的类型定义及其各个操作的算法描述以及代码实现
编程完成一元多项式的建立、遍法运算、减法运算、乘法运算等算法功能及实现。
代码
#include<iostream>
#include<malloc.h> /* malloc()等 */
#include<stdio.h>
#include<process.h>
#include<math.h>
using namespace std;
struct Elemtype //数据
{
double c;
int e;
};
struct Lnode //结点
{
Elemtype data;
Lnode *next;
};
class Link //链表类
{
public:
Lnode *head,*tail;
int len;
Link() //构造函数,空链表
{
Lnode *p;
p=(Lnode*)malloc(sizeof(Lnode));
head=tail=p;
tail->next=NULL;
len=0;
}
Link(const Link &L) //深复制构造函数
{
Lnode *p=L.head->next,*q;
q=(Lnode*)malloc(sizeof(Lnode));
head=tail=q;
tail->next=NULL;
len=0;
while(p)
{
q=(Lnode*)malloc(sizeof(Lnode));
q->data=p->data;
p=p->next;
Incert(q);
}
}
int Incert(Lnode *);
void Input(int);
void print();
friend Link operator+(Link,Link);
friend Link operator-(Link,Link);
friend Link operator*(Link,Link);
};
int Link::Incert(Lnode *q) //插入结点
{
Lnode *p=head;
if(!len)
{
tail->next=q;
tail=tail->next;
tail->next=NULL;
len++;
return 1;
}
while(p->next)
{
if(p->next->data.e>q->data.e)
{
q->next=p->next;
p->next=q;
len++;
return 1;
}
else if(p->next->data.e==q->data.e)
{
p->next->data.c+=q->data.c;
return 1;
}
p=p->next;
}
p->next=q;
q->next=NULL;
len++;
return 1;
}
void Link::Input(int l) //创建输入一元多项式
{
cout<<"请按顺序输入"<<l<<"组系数、指数:"<<endl;
double c;
int e;
Lnode *q;
for(int i=0;i<l;i++)
{
q=(Lnode*)malloc(sizeof(Lnode));
cin>>c>>e;
q->data.c=c;
q->data.e=e;
Incert(q);
}
}
void Link::print() //输出一元多项式
{
Lnode *p=head;
while(p->next->next)
{
p=p->next;
cout<<"("<<p->data.c<<"x^"<<p->data.e<<")+";
}
p=p->next;
cout<<"("<<p->data.c<<"x^"<<p->data.e<<")"<<endl;
}
Link operator +(Link La,Link Lb) //相加
{
Link la=La,lb=Lb;
Lnode *pb=lb.head->next,*p;
while(pb->next)
{
p=pb;
pb=pb->next;
la.Incert(p);
}
la.Incert(pb);
return la;
}
Link operator -(Link La,Link Lb) //相减
{
Link la=La,lb=Lb;
Lnode *pb=lb.head->next;
while(pb)
{
pb->data.c=-pb->data.c;
pb=pb->next;
}
return la+lb;
}
Link operator *(Link La,Link Lb)
{
Link Lc;
Lnode *pa=La.head->next,*q;
while(pa)
{
Lnode *pb=Lb.head->next;
while(pb)
{
q=(Lnode*)malloc(sizeof(Lnode));
q->data.c=(pa->data.c )*( pb->data.c);
q->data.e=(pa->data.e)+( pb->data.e);
Lc.Incert(q);
pb=pb->next;
}
pa=pa->next;
}
return Lc;
}
int main()
{
Link A,B;
int l1,l2;
cout<<"//建立一元多项式A..."<<'\n'<<"请输入A的项数:";cin>>l1;
A.Input(l1);
cout<<"//建立一元多项式B..."<<'\n'<<"请输入B的项数:";cin>>l2;
B.Input(l2);
cout<<endl;
cout<<"一元多项式A:";A.print();
cout<<"一元多项式B:";B.print();
cout<<endl;
cout<<"多项式相加:";(A+B).print();
cout<<"多项式相减:";(A-B).print();
cout<<"多项式乘法:";(A*B).print();
}