【数据结构与算法】第三章 表c实现应用一-----------多项式

可以用表来定义一种关于一元多项式的抽象数据类型。若最高幂数比较小,使用数组来存储幂系数是比较简单的;但如果出现幂数跨度比较大的情况,使用链表结构存储是比较合适的。具体内容参见《数据结构与算法分析:c语言描述》第三种。这里先实现了数组存储数据的简单情况。代码如下:

  
    
#include < stdio.h >
#include
< stdlib.h >

#define MaxDegree 10

typedef
struct _Polynomial
{
int CoeffArray[ MaxDegree + 1 ];
int HighPower;
}
* Polynomial;


// Max
int Max( int a, int b )
{
if ( a >= b )
return a;
else
return b;
}

// zero
void
ZeroPolynomial( Polynomial Poly )
{
int i;
for ( i = 0 ; i <= MaxDegree; i ++ )
Poly
-> CoeffArray[ i ] = 0 ;
Poly
-> HighPower = 0 ;
}

// add
void
AddPolynomial(
const Polynomial Poly1,
const Polynomial Poly2,
Polynomial PolySum )
{
int i;
ZeroPolynomial( PolySum );
PolySum
-> HighPower = Max( Poly1 -> HighPower, Poly2 -> HighPower );
for ( i = PolySum -> HighPower; i >= 0 ; i -- )
PolySum
-> CoeffArray[i] = Poly1 -> CoeffArray[i] + Poly2 -> CoeffArray[i];
}

// multiplication
void
MultPolynomial(
const Polynomial Poly1,
const Polynomial Poly2,
Polynomial PolyProd )
{
int i, j;

ZeroPolynomial( PolyProd );
PolyProd
-> HighPower = Poly1 -> HighPower + Poly2 -> HighPower;

if ( PolyProd -> HighPower > MaxDegree )
perror(
" Exceeded array size.\n " );
else
for ( i = 0 ; i <= Poly1 -> HighPower; i ++ )
for ( j = 0 ; j <= Poly2 -> HighPower; j ++ )
PolyProd
-> CoeffArray[i + j] += Poly1 -> CoeffArray[i]
* Poly2 -> CoeffArray[j];
}

// print
void
PrintPolynomial(
const Polynomial Poly )
{
int i;
printf(
" F(x) = " );
for ( i = 0 ; i <= Poly -> HighPower; i ++ )
{
if ( Poly -> CoeffArray[i] == 0 )
continue ;
else
{
printf(
" %d*X[%d] " , Poly -> CoeffArray[i], i );
if ( i != Poly -> HighPower - 1 )
printf(
" + " );
}
}
}

/* ************************************************************ */
int main()
{
int i;
Polynomial poly1, poly2, polysum, polyprod;

poly1
= ( Polynomial )malloc( sizeof ( struct _Polynomial ) );
poly2
= ( Polynomial )malloc( sizeof ( struct _Polynomial ) );
polysum
= ( Polynomial )malloc( sizeof ( struct _Polynomial ) );
polyprod
= ( Polynomial )malloc( sizeof ( struct _Polynomial ) );

ZeroPolynomial( poly1 );
ZeroPolynomial( poly2 );

for ( i = 0 ; i < 5 ; i ++ )
{
poly1
-> CoeffArray[i] = i ;
poly2
-> CoeffArray[i] = i + 1 ;
}

poly1
-> HighPower = i - 1 ;
poly2
-> HighPower = i;

AddPolynomial( poly1, poly2, polysum );
MultPolynomial( poly1, poly2, polyprod );

printf(
" \npoly1: " );
PrintPolynomial( poly1 );
printf(
" \npoly2: " );
PrintPolynomial( poly2 );
printf(
" \npolysum: " );
PrintPolynomial( polysum );
printf(
" \npolyprod: " );
PrintPolynomial( polyprod );
printf(
" \n " );
}

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