多项式ADT笔记(数据结构c版)
项式ADT笔记
设多项式为P=A1Xn1+A2Xn2+···AiXni
//多项式ADT的数组实现 typedef struct { int CoeffArray[MaxDegree + 1];//各个多项式的系数A int HighPower; //最高的幂ni } * Polynomial; //将多项式初始化为零的过程 void ZeroPolynomial(Polynomial Poly) { int i; for( i = 0; i <= MaxDegree; i ++) Poly -> CoeffArray[i] = 0; Poly -> HighPower = 0; } //多项式相加 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]; } //多项式相乘 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) Error("Exceeded array size"); 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]; }
c/c++ 传统数组的缺点
使用链表实现
typedef struct Node* PtrToNode;//Node对象 struct Node { int Coefficient;//系数A int Exponent;//幂 PtrToNode Next;//下一个Node的指针 }; typedef PtrToNode Polynomail;//下一个Node对象