多项式相加 单链表实现

来源:互联网 发布:vb.net 实例化 编辑:程序博客网 时间:2024/05/23 12:52

2题目:

实现多项式相加

具体的算法步骤以后再补,先把代码贴上

首先是头文件

#include<cstdio>#include<iostream>using namespace std;//项的定义class TermType{public :float coef;int expn;};//节点的定义class PNode{public :TermType term;PNode *next;public :PNode(float c=0,int e=0){term.coef=c;term.expn=e;next=NULL;}};//单链多项链表的定义class PolynList{private:PNode *head;int length;public :PolynList(int l=0){l=length;}//链表的初始函数void SetLength(int l){l=length;}void Create(int n,float a[][2]);void AddPolyn(PolynList &);void PrintPolynList();void SubreactPolyn(PolynList&){}void MultiplyPolyn(PolynList &){}void AddPNode(int,float);//以后面的指数为目标添加void DeletePolyn();//完成加减运算完后删除前面引数为0的节点};void PolynList::Create(int n,float a[][2])//n为数组长度 2为宽度 其中记录了多项式的引数和指数{PNode *p=head;p=head=new PNode();(*head).next=NULL;length=n;for(int i=0;i<n;i++){(*p).next=new PNode(a[i][0],a[i][1]);p=(*p).next;if(i==n-1){(*p).next=NULL;}}}void PolynList::AddPNode(int e,float f=0)//e{PNode *p=head;while(p){if((*p).term.expn==e){return ;}if((*p).term.expn<e){if((*p).next==NULL){(*p).next=new PNode(f,e);(*(*p).next).next=NULL;length++;}if((*(*p).next).term.expn>e){PNode *temp=(*p).next;    (*p).next=new PNode(f,e);    p=(*p).next;    (*p).next=temp;    length++;    return ;}}p=(*p).next;}}void PolynList::DeletePolyn(){PNode *p=head;p=(*p).next;while(p){if((*p).term.coef==0){if((*p).next==NULL){PNode *p2=head;while(p2){if((*p2).next==p){(*p2).next=NULL;length--;}p2=(*p2).next;}}else {PNode *p2=head;while(p2){if((*p2).next==p){(*p2).next=(*p).next;length--;}p2=(*p2).next;}}}p=(*p).next;}}void PolynList::AddPolyn(PolynList& pList)//地址传递 传的为需要运算的另一个个链表{PNode *p1=head,*p2=pList.head;p1=(*p1).next,p2=(*p2).next;while(p1&&p2)//p1 p2 指向不为空{if(((*p1).term.expn)<((*p2).term.expn)){p1=(*p1).next;}else if(((*p1).term.expn)>((*p2).term.expn)){AddPNode((*p2).term.expn,(*p2).term.coef);p2=(*p2).next;}else if(((*p1).term.expn)==((*p2).term.expn)){(*p1).term.coef+=(*p2).term.coef;p1=(*p1).next,p2=(*p2).next;}}if(p1){return;}if(p2){while(p2){AddPNode((*p2).term.expn,(*p2).term.coef);p2=(*p2).next;}}}void PolynList::PrintPolynList(){PNode *p=head;p=(*p).next;if(length==0){cout<<"多项式为空!"<<endl;}else {cout<<"P(X)=";    for(int i=0;i<length;i++)   {   cout<<(*p).term.coef<<"x^"<<(*p).term.expn;   p=(*p).next;   if(p){cout<<"+";}   } }cout<<endl;}


 

然后是main函数的cpp文件

/*2014-3-14 单链表实现多项式的计算*/#include<iostream>#include"hTest2.h"using namespace std;int main(){PolynList p1,p2;float a[][2]={{1,2},{2,3},{4,5}};float b[][2]={{2,1},{-2,3},{2,4},{2,6}};p1.Create(3,a);//创建链表1p2.Create(4,b);//创建链表2p1.PrintPolynList();//链表1输出p2.PrintPolynList();//链表2输出p1.AddPolyn(p2);//链表1+链表2p1.DeletePolyn();//链表1清除引数为0的项p1.PrintPolynList();//打印经过加法计算的链表1return 1;}


 

0 0