純粋なC言語の単鎖の表は1元の多項式の値を求めるアルゴリズムを解くことを実現します(本の上のコード)


/*Polynomial.h*/
#ifndef POLYNOMIAL_H_INCLUDED
#define POLYNOMIAL_H_INCLUDED
#include 
#include 
#include 
#include 

typedef struct node
{			//        
    double coef;					//  
    int exp;						//  
    struct node *link;			//    
} Term, *Polynomial;			//        



#endif // POLYNOMIAL_H_INCLUDED

/*test.c*/
#include "Polynomial.h"
#define maxSize 30

void Input ( Polynomial PL, double C[ ], int E[ ], int n )
{
//     C[n]     E[n]          ,           
//      PL。        PL       
    Polynomial newTerm, p, pre;
	int i;
	for ( i = 0; i < n; i++ )
    {						//          
		p = PL->link;
		pre = PL;				//           
		while ( p != NULL && p->exp > E[i] )
		{
		    pre = p;
            p = p->link;
        }
		if ( p != NULL && p->exp == E[i] ) 		//        ,   
 			printf ( "     %d    ,    
", E[i] ); else { newTerm = ( Term* ) malloc ( sizeof ( Term ) ); // newTerm->coef = C[i]; newTerm->exp = E[i]; newTerm->link = p; pre->link = newTerm; // } } } void Output ( Polynomial PL ) { // PL。 Polynomial p = PL->link; printf ( "The polynomal is:
" ); bool h = 1; // ‘+’ while ( p != NULL ) { if ( h == 1 ) { if ( p->coef < 0 ) printf ( "-" ); // "-" h = 0; } else { // if ( p->coef > 0 ) printf ( "+" ); else printf ( "-" ); } if ( p->exp == 0 || fabs(p->coef) != 1 ) printf ( "%g", fabs(p->coef) ); // switch ( p->exp ) { // case 0: break; // case 1: printf ( "X" ); break; // “X” default: printf ( "X^%d", p->exp ); // “X^ ” } p = p->link; // } printf ( "
" ); } void reverse ( Polynomial A ) { // A , 。 Polynomial p, q; p = A->link; A->link = NULL; // while ( p != NULL ) { q = p; p = p->link; // *q q->link = A->link; A->link = q; // *q } } double calcValue_1 ( Polynomial A, double x ) { // 。pow(x, y) x y , “math.h” Polynomial p = A->link; double value = 0.0; while ( p != NULL ) { value = value + pow(x, p->exp) * p->coef; p = p->link; } return value; } double calcValue ( Polynomial PL, double x ) { // 。pow(x, y) x y , "math.h" Polynomial p = PL->link; double value = p->coef; int e = p->exp; // am em p = p->link; //p (am-1, em-1) while ( p != NULL ) { value = value*pow ( x, e-p->exp )+p->coef; // e = p->exp; p = p->link; //e ei-1 } return value*pow ( x, e ); } int main() { double C[maxSize] = {3, -2, 1, 4, -6, -1 }; int E[maxSize] = {6, 5, 3, 2, 1, 0 }; int n = 6; Polynomial Poly; double x; Poly = ( Term* ) malloc ( sizeof ( Term ) ); Poly->link = NULL; Input ( Poly, C, E, n ); Output ( Poly ); printf ( "
" ); x = 10; printf ( "x=%g %g
", x, calcValue ( Poly, x ) ); printf ( "x=%g %g
", x, calcValue_1 ( Poly, x ) ); reverse ( Poly ); Output ( Poly ); }