多项式相加单链表实现

来源:互联网 发布:nginx整合php 编辑:程序博客网 时间:2024/06/05 09:14
#include<iostream>using namespace std;struct PolyNode{double coef;int exp;PolyNode *next;};class PolyClass{PolyNode *head;//单链表的头结点指针public:PolyClass();~PolyClass();void Disp();void CreateList(double a[],int b[],int n);void Sort();friend void PolyAdd(PolyClass &,PolyClass &,PolyClass &);};PolyClass::PolyClass(){head=new PolyNode();head->next=NULL;}PolyClass::~PolyClass(){PolyNode *pre,*p;pre=head,p=pre->next;while(p!=NULL){delete pre;pre=p;p=p->next;}delete pre;}void PolyClass::CreateList(double a[],int b[],int n){int i;PolyNode *s,*r;r=head;for(i=0;i<n;i++){s=new PolyNode();s->coef=a[i];s->exp=b[i];r->next=s;r=s;}r->next=NULL;}void PolyClass::Disp(){bool flag=true;PolyNode *p;p=head->next;while(p!=NULL){if(flag) flag=false;else if(p->coef>0)cout<<'+';if(p->exp==0)cout<<p->coef;else if(p->exp==1)cout<<p->coef<<'x';else cout<<p->coef<<"x^"<<p->exp;p=p->next;}cout<<endl;}void PolyClass::Sort()//指数域递减排序{PolyNode *p,*q,*pre;q=head->next;if(q==NULL)return;p=q->next;if(p==NULL)return;q->next=NULL;//构造只含有一个数据节点的单链表//重要while(p!=NULL){q=p->next;//不断遍历下一个结点pre=head;//每次从头扫描while(pre->next!=NULL&&pre->next->exp>p->exp)pre=pre->next;//找到要插入的位置p->next=pre->next;pre->next=p;p=q;}}void PolyAdd(PolyClass &poly1,PolyClass &poly2,PolyClass &poly3){PolyNode *pa=poly1.head->next;PolyNode *pb=poly2.head->next;PolyNode *s,*r;r=poly3.head;double c;while(pa!=NULL&&pb!=NULL){if(pa->exp<pb->exp){s=new PolyNode();s->coef=pb->coef,s->exp=pb->exp;r->next=s;r=s;pb=pb->next;}else if(pa->exp>pb->exp){s=new PolyNode();s->coef=pa->coef,s->exp=pa->exp;r->next=s;r=s;pa=pa->next;}else{c=pa->coef+pb->coef;if(c!=0){s=new PolyNode();    s->coef=c,s->exp=pa->exp;    r->next=s;    r=s;}pa=pa->next,pb=pb->next;}}if(pb!=NULL)pa=pb;while(pa!=NULL){s=new PolyNode();s->coef=pa->coef,s->exp=pa->exp;r->next=s;r=s;pa=pa->next;}r->next=NULL;}int main(){PolyClass poly1,poly2,poly3;double a[20];int b[20],n;a[0]=2.0;b[0]=3;a[1]=3.2;b[1]=5;a[2]=-6.0;b[2]=1;a[3]=10.0;b[3]=0;n=4;poly1.CreateList(a,b,n);poly1.Sort();poly1.Disp();a[0]=6.0,b[0]=1;a[1]=1.8,b[1]=5;a[2]=-2.0,b[2]=3;a[3]=1.0,b[3]=2;a[4]=-2.5,b[4]=4;a[5]=-5.0,b[5]=0;n=6;poly2.CreateList(a,b,n);poly2.Sort();poly2.Disp();PolyAdd(poly1,poly2,poly3);poly3.Disp();return 0;}

0 0