数据结构示例之简单多项式相加

以下为展示简单多项式相加的示例:

1.用c语言实现的版本

#include 
#include
#define  MAX_TERMS 100    /* size of terms array */

//定义多项式的节点
typedef struct 
{
	float coef; //系数
	int expon; //指数
} polynomial;

polynomial  termsA[MAX_TERMS]; //加数A
polynomial  termsB[MAX_TERMS]; //加数B
polynomial  termsD[MAX_TERMS]; //和D
int avail = 0; //D中的已用节点数

/* 比较指数大小 */
int COMPARE(int coef1,int coef2) 
{
	if (coef1 < coef2) 
	{	
		return -1;
	} 
	else if (coef1 == coef2) 
	{	
		return 0;
	}
	else
	{
		return 1;
	}
}

/* 加一个新项到多项式中 */
void attach(float coefficient, int exponent)
{  
	if (avail > MAX_TERMS)  
	{
		printf("Too many terms in the polynomial \n");
		exit(1);
	}
	termsD[avail].coef = coefficient; //系数
	termsD[avail++].expon = exponent; //指数
}

/* 多项式相加:A(x)+B(x)=D(x) */
void padd(int starta, int finisha, int startb, int finishb, int *startd,int *finishd)
{ 
	float coefficient; //系数
	*startd = avail;
	while ( starta <= finisha && startb <=finishb)
	{	
		switch (COMPARE(termsA[starta].expon, termsB[startb].expon))  
		{
		case -1:  /* a指数小于b指数*/
			attach(termsA[starta].coef, termsA[starta].expon);
			++starta;
			break;
		case 0:  /* 两指数相等,系数相加 */
			coefficient = termsA[starta].coef + termsB[startb].coef;
			if (coefficient)
			{	
				attach(coefficient, termsA[starta].expon);
			}
			++starta;
			++startb;
			break;
		case 1:  /* a指数大于b指数 */
			attach(termsB[startb].coef,termsB[startb].expon);
			++startb;
			break;
		}
	}
	/* 把其余的A(x)相加 */
	for ( ; starta <= finisha;  ++starta)
	{	
		attach(termsA[starta].coef,termsA[starta].expon);
	}
	/* 把其余的B(x)相加 */
	for ( ; startb <= finishb;  ++startb)
	{	
		attach(termsB[startb].coef,termsB[startb].expon);
	}
	*finishd = avail -1;
}

void main()
{
	int starta=0, finisha=2; //A多项式节点的下标
	int startb=1, finishb=5; //B多项式节点的下标
	int startd,finishd; //D多项式节点的下标
	for (int i=0; i< MAX_TERMS; ++i) 
	{
		termsA[i].coef = 0;
		termsA[i].expon = 0;
		termsB[i].coef = 0;
		termsB[i].expon = 0;
		termsD[i].coef = 0;
		termsD[i].expon = 0;
	}

	for(int i=starta; i<=finisha; ++i)
	{
		termsA[i].coef = i+1;
		termsA[i].expon = i+1;
	}

	for(int i=startb; i<=finishb; ++i)
	{
		termsB[i].coef = i+1;
		termsB[i].expon = i+1;
	}

	printf("多项式A:\n");
	for(int i=starta; i<=finisha; ++i)
	{
		printf("系数%f,指数%d\n", termsA[i].coef, termsA[i].expon);
	}

	printf("多项式B:\n");
	for(int i=startb; i<=finishb; ++i)
	{
		printf("系数%f,指数%d\n", termsB[i].coef, termsB[i].expon);
	}

	padd(starta,finisha,startb,finishb,&startd,&finishd);

	printf("多项式D:\n");
	for(int i=startd; i<=finishd; ++i)
	{
		printf("系数%f,指数%d\n", termsD[i].coef, termsD[i].expon);
	}
}
运行结果如下图所示:

数据结构示例之简单多项式相加_第1张图片

你可能感兴趣的:(数据结构)