链表实现多项式操

最近看了weiss的数据结构,想记录一下自己的代码,这里是一个关于链表实现多项式的相关操作。

/***************************************
*@function:数据结构第三章,链表实现多项式的加减,乘也是类似,只不过还要合并,合并比较麻烦;
*@data:2015/5/8
*@Author:lss
************************************/

#include <stdio.h>
#include <iostream>
using namespace std;


#define  N1  2     
#define  N2  3


typedef 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 for the number you want create
polyNomial *p = poly;
float co;
int po;
while(N != 0){    
N--;
polyNomial *tmp = (polyNomial*)malloc(sizeof(polyNomial));
cout<<"please input the coef:"<<endl;
cin>>co;
tmp->info.coef = co;


cout<<"please input the power:"<<endl;
cin>>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<<p->info.coef<<"X"<<p->info.power<<"+";
}
cout<<endl;
}
//增加一个多项式中的元素,直接插在首节点的位置。
polyNomial * addone(polyNomial * poly , polyNode node){
polyNomial * tmp = (polyNomial *) malloc(sizeof(polyNomial));
tmp->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;
}


你可能感兴趣的:(链表实现多项式操作)