stefan1240的专栏

最近看了weiss的数据结构,想记录一下自己的代码,这里是一个关于链表实现多项式的相关操作。/**************************************@function:数据结构第三章,链表实现多项式的加减,乘也是类似,,只不过还要合并,合并比较麻烦;*@data:2015/5/8*@Author:lss************************************/#include #include using namespace std;#define N1 2 #define N2 3typedef struct polyNode{float coef; //store 系数int power; // store 幂}polyNode;typedef struct polyNomial{polyNode info;polyNomial *next;}polyNomial;//创建一个多项式,输入为多项式的头结点和元素的个数,返回:合并后的首节点polyNomial *creatPoly(polyNomial * poly,int N){ //N stand the number you want createpolyNomial *p = poly;float co;int po;while(N != 0){ N–;polyNomial *tmp = (polyNomial*)malloc(sizeof(polyNomial));cout<<"please input the coef:"<>co;tmp->info.coef = co;cout<<"please input the power:"<>po;tmp->info.power = po;p->next = tmp;p = p->next; //p指向下一个位置}poly = poly->next;p->next = NULL;return poly;}//显示多项式void display(polyNomial * poly){if (poly ==NULL){cout<<"null"<<endl;;}cout<<"f(x)=";for ( polyNomial * p = poly; p !=NULL; p=p->next ){cout<info.coef<<"X"<info.power<<"+";}cout<info = node;tmp->next = poly;return tmp;}//加减方式合并两个多项式polyNomial * addPoly(polyNomial* poly1, polyNomial* poly2){int flag = 0;for( polyNomial * p1=poly1; p1!=NULL; p1 = p1->next){flag = 0;for (polyNomial *p2 = poly2; p2!=NULL; p2 = p2->next){if (p1->info.power == p2->info.power){p2->info.coef = p2->info.coef + p1->info.coef;flag =1;break;}}if (flag ==0) //多项式二中没有跟多项式一中相同的那一项,则在多项式二中增加一个。{poly2 = addone(poly2, p1->info);}}return poly2;}//主函数int main(){polyNomial *poly1 = (polyNomial*)malloc(sizeof(polyNomial)); //得到第一个多项式,poly1 = creatPoly(poly1,N1);display(poly1);polyNomial *poly2 = (polyNomial*)malloc(sizeof(polyNomial)); //得到第二个多项式poly2 = creatPoly(poly2,N2);display(poly2);poly2 = addPoly(poly1,poly2); //加减合并两个多项式display(poly2);return 0;}

地球仍然转重,世间依旧善变,而我永远爱你。

stefan1240的专栏

相关文章:

你感兴趣的文章:

标签云: