本人要做一个多项式运算的作业,可是 不会做,希望各位大侠帮忙。
就是用链表来编写一个程序,实现多项式的各项运算。其中要用到链表类,链表游标类,链表节点类。
多项式这样输入的:例如2x^3+3x^8
希望可以给出完整的程序。希望高手速回。谢谢!!!!!!
#include<iostream.h>
typedef int ElemType;
struct Pnomial //Pnomial=Polynomial(多项式) { ElemType co,de; //co=coefficient(系数), de=degree(次数)
Pnomial* next; };
void main() { Pnomial *ph,*p,*q; //ph表头指针,p移动指针,q临时储存结点
ph=p=new Pnomial;
cout<<"\nthe 1st Polynomial:"<<endl; cout<<"give coefficient value:"<<endl;
while(p->co!=0) { q=new Pnomial;
cin>>q->co; if(q->co!=0) { cout<<"x^"; cin>>q->de; cout<<"+"; }
p->next=q; p=q; }
q->de=886; //一个链表储存两个多项式,以X的886次方为界
cout<<"the 1st Polynomial end."<<endl; cout<<"\nthe 2nd Polynomial:"<<endl; cout<<"give coefficient value:"<<endl;
do { q=new Pnomial;
cin>>q->co; if(q->co!=0) { cout<<"x^"; cin>>q->de; cout<<"+"; }
p->next=q; p=q; } while(p->co!=0);
cout<<"the 2nd Polynomial end."<<endl;
p->next=NULL; p=ph->next;
cout<<'\n'<<endl; cout<<"the 1st Polynomial:"<<endl;
while(p->next!=NULL) { if(p->de==886) { cout<<'\n'<<endl; cout<<"the 2nd Polynomial:"<<endl; p=p->next; } else if(p!=ph->next) cout<<" + ";
if(p->co!=1) cout<<p->co;
if(p->de!=0) { cout<<"x"; if(p->de!=1) cout<<"^"<<p->de; }
p=p->next; } cout<<'\n'<<endl;
//以上代码实现输入和打印
//以下代码实现系数相加并打印结果
p=ph->next; Pnomial *re,*di,*temp; //新建一个链表储存结果 //re=result(结果), di=displace(移动指针)
Pnomial *ap; //删除链内结点时临时存放指针位置的链外结点
ap=NULL;
int counter=0; //计数变量,记录p赋值给temp的起始结点
re=di=new Pnomial;
while(p->next!=NULL) { temp=new Pnomial; temp->co=p->co; temp->de=p->de;
while(p->next!=NULL) { ap=p; //暂时存放前一个结点的指针地址
p=p->next; //当前待处理结点
if(p->de==886) continue;
if(p->de==temp->de) { temp->co=temp->co+p->co; //次数一样则加进temp->co
//实际上就是删除加了进去temp->co的结点 if(p==NULL) ap->next=p; //NULL时不用跳过 else ap->next=p->next; //跳过p指向p->next p=ap; //把地址还给p指针 } }
di->next=temp; di=temp;
p=ph->next; //p指针每处理完一次都先返回到表头结点
counter++; for(int i=0;i<counter;i++) p=p->next;
if(p->de==886) { p=p->next; counter++; } }
di->next=NULL;
cout<<"the result Polynomial:"<<endl;
di=re->next; //di回到表头结点,准备打印结果多项式
while(di!=NULL) { if(di!=re->next) cout<<" + ";
if(di->co!=1) cout<<di->co;
if(di->de!=0) { cout<<"x"; if(di->de!=1) cout<<"^"<<di->de; }
di=di->next; }
cout<<'\n'<<endl; }