c++用链表实现一元多项方程式

来源:互联网 发布:赛维网络面试 编辑:程序博客网 时间:2024/05/16 12:28

一元多项方程式的实现主要在于加减法。其主要有系数和指数,如果用顺序表来表示,最大指数如果很大比如1000,但是中间又有很多指数没有,所以会浪费很多空间,所以用链表来实现虽然麻烦但是节约空间,下面来看算法的实现

一:这是节点的结构体

#include<iostream>
using namespace std;
struct Item
{
 double coef;
 int expn;
 Item *next;
 Item();
};


Item::Item()
{
coef=0;
next=NULL;
}

二:list_cometrue.h为实现方法的类

#include"link_list.h"


class List
{
protected:
Item *head;
public:
void Init();
List();
~List();
void create(double co[],int ex[],int p);//创建链表
void out();
int length();//求链表p的长度
void getelem(int position,Item *p);//返回指定位置的结构为*p;
List operator+(const List &p1);


};


 void List::Init()
{
head=new Item;
}


 List::List()
 {
 Init();
 }


 List::~List()
 {
 }


 void List::create(double co[],int ex[],int p)//创建链表
{
Item *ptr,*p2;
ptr=head;
  for(int i(0);i<p;i++)
  {
p2=new Item; 
    p2->coef=co[i];
    p2->expn=ex[i];
    ptr->next=p2;
ptr=p2;   
  }
  
 
 }


 void List::out()//输出链表
 {//Item *ptr=p.head;
    for(Item *ptr=head->next;ptr!=NULL;ptr=ptr->next)
{
cout<<ptr->coef<<"^"<<ptr->expn<<"+";


}
cout<<endl;
 }


 int List::length()
 {
 int count(0);
 for(Item *ptr=head->next;ptr!=NULL;ptr=ptr->next)
 count++;
 return count;
 }


 void List::getelem(int position,Item *p)//取指定位置的节点复制给p
 {Item *ptr=head->next;
   if(position<0||position>length())
   {
   cout<<"不存在这个元素"<<endl;
   }else{
   //Item *ptr=head->next;
   for(int i(0);i!=position;ptr=ptr->next,i++)
   {
   p->coef=ptr->coef;
   p->expn=ptr->expn;
   } 
   }
 }
 


List List::operator+(const List &p1)//运算符重载实现加法,
{    
Item *la=head->next;
     Item *lb=p1.head->next;
 List List_link;
 Item *lc=List_link.head;
 cout<<"shifoujinru"<<endl;

    while(la!=NULL&&lb!=NULL)
{
 if(la->expn>lb->expn)
 {
 lc->next=lb;
 lb=lb->next;
 lc=lc->next;
 }else if(la->expn<lb->expn){
 lc->next=la;
 la=la->next;
      lc=lc->next;
 }else{
 la->coef=la->coef+lb->coef;
 lc->next=la;
 la=la->next;
 lb=lb->next;
 lc=lc->next;
 }
}
if(la==NULL)
{
for(;lb!=NULL;lb=lb->next)
{
lc->next=lb;
lc=lc->next;
}
}else
{
for(;la!=NULL;la=la->next)
{
lc->next=la;
lc=lc->next;
}
}



   return List_link;
 }这个难点在于最后一个一元多项式加法的实现,这里用了运算符的重载,

其中实现时应注意判断条件最后按照指数的从大到小的顺序来输出

三:main函数

#include"list_cometrue.h"


void main()
{
   List p,p1,p2;//p2为加厚的类
   double co[5]={5,4,3,2,1};
   int ex[5]={1,2,3,4,5};
   int num=sizeof(co)/sizeof(co[1]);
   p.create(co,ex,num);
   p.out();
   double co1[]={1,2,4,3,6,3,5};
   int ex1[]={1,3,3,4,5,6,7};
   int num1=sizeof(co1)/sizeof(co1[1]);
   p1.create(co1,ex1,num1);/创建函数
   p1.out();输出函数
   p2=p+p1;  //重载运算符 书实现链表想加
   p2.out();
 
   }
   

}



    同理减法也是这样实现,只是要注意判断条件

0 0
原创粉丝点击