主题:请问关于多项式的加减的算法与程序?谢谢
dongfengaa
[专家分:0] 发布于 2008-03-29 22:05:00
[em10][em10]
回复列表 (共2个回复)
沙发
csea [专家分:340] 发布于 2008-04-02 21:41:00
用链表实现,设多项式的最高次为N,则申请长度为N的链表对多项式进行存储,之后进行加减时只要把相应的结点相加减即可
板凳
luxx [专家分:4190] 发布于 2008-04-12 20:45:00
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct Ploynode
{
int exp;
double ceof;
Ploynode *next;
}Ploynode,*Ploylist;
Ploynode* ploycreat()
{
Ploynode *head,*rear,*s;
double c;
int e;
head=(Ploynode*)malloc(sizeof(Ploynode));
rear=head;
cout<<"按照指数的升序输入系数和指数,输入0和0结束:\n";
cin>>c>>e;
double EXP=0.00001;
while(!((c>-EXP)&&(c<EXP)))
{
s=(Ploynode*)malloc(sizeof(Ploynode));
s->ceof=c;
s->exp=e;
rear->next=s;
rear=s;
cin>>c>>e;
}
rear->next=NULL;
return head;
}
//传递实参的时候ploya的长度>=ployb
void Ployadd(Ploynode* ploya,Ploynode* ployb)
{
Ploynode *p,*q,*tail,*temp;
double sum;
p=ploya->next;
q=ployb->next;
tail=ploya;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{ tail->next=p; tail=p; p=p->next;}
else if(p->exp==q->exp)
{
sum=p->ceof+q->ceof;
double EXP=0.00001;
if(!((sum>-EXP)&&(sum<EXP)))
{
p->ceof=sum;
tail->next=p;
tail=p;
p=p->next;
temp=q; q=q->next; free(temp);
}
else
{
temp=p; p=p->next; free(temp);
temp=q; q=q->next; free(temp);
}
}
else
{
tail->next=q; tail=q;
q=q->next;
}
}//while
while(p!=NULL) //把ploya剩余的链接上去
{
tail->next=p;
tail=p;
p=p->next;
}
}
void Output(Ploynode* head) //打印多项式
{
Ploynode *p=head->next;
while(p)
{
cout<<p->ceof;
if(p->exp) cout<<"*x^"<<p->exp;
if(p->next&&(p->next->ceof)>0) cout<<"+";
p=p->next;
}
}
void ListDestroy(Ploynode* &L)// 删除所有节点
{
if (!L||!(L->next)) return ;
Ploynode* p;
p=L;
while(L)
{
L=p->next;
free(p);
p=L;
cout<<"free memory"<<endl;
}
}
int main()
{
Ploynode *ploya=ploycreat();
cout<<"\n Ploynode A:\n";
Output(ploya);
cout<<endl;
Ploynode *ployb=ploycreat();
cout<<"\n Ploynode B:\n";
Output(ployb);
cout<<endl;
Ployadd(ploya,ployb);
cout<<"Ploy A + B = \n";
Output(ploya);
cout<<endl;
ListDestroy(ploya);
system("pause");
return 0;
}
我还写过相乘的,不过是用STL 做的
我来回复