数据结构第2章精要.ppt

数据结构第2章精要

第2章 线性表 ;2.1 线性表与数组 ; ; 假设线性表的元素类型是浮点数,其ADT定义为: class LinearList { // 对象: L = ( a0, a1, …, an-1) 或 ( ), ai?浮点数, 0≤i n public: LinearList ( ); // 构造函数,创建一个空表 int Length( ); // 返回该实例的长度 void LeftToRight( ); // 从左到右遍历全部元素 float Retrieve( int i ); // 返回第i个元素的值 void Store( int i, float v ); // 将v的值赋予第i个元素 void Insert( int i, float v ); // 将v作为第i个元素插入 float Delete( int i ); // 删除第i个元素并返回其值 };; 如何表示线性表的结构,从而高效实现这些操作? 最通常的方法是用程序设计语言提供的数组,即用数组的第i个单元表示线性表的ai元素。 数组第i个单元与第i+1个单元在物理上是连续存放的,因此称上述方法为顺序映射(sequential mapping)。 顺序映射使随机存取表中的任何元素的时间是O(1),但插入和删除第i个元素将导致其后续元素的迁移。 ;2.2 多项式 ; int operator ! ( ); // 若 *this 是零多项式返回1,否则返回0 float Coef (int e); // 返回*this 中指数为e 的项的系数 int LeadExp ( ); // 返回*this 中最大指数 void AddTerm (int e, float c); // 将 e, c 加入*this Polynomial Add (Polynomial poly); // 返回多项式 *this 与 // poly之和 Polynomial Mult (Polynomial poly); // 返回多项式 *this 与 // poly之积 float Eval ( float f); // 计算并返回x = f时*this 多项式的值 };;2.2.1 多项式的表示 ;方法2 当p.degree MaxDegree时,方法1很浪费空间,可动态定义coef数组的元素个数: private: int degree; float *coef; 构造函数为: Polynomial::Polynomial( int d) { degree = d; coef = new float [degree+1]; // 动态申请数组空间 };方法3 对于有很多零项的稀疏多项式,方法2仍然很浪费空间。例如x800+3仅有2个非零项,其余799项都是零项。这时,只存储非零项更为有效。由此将多项式表示为另一种形式:;term定义如下: class Polynomial; // 向前声明 class term { friend Polynomial; private: float coef; // 系数 int exp; // 指数 };;Polynomial的私有成员定义如下: private: static term termArray[MaxTerms]; // 静态成员声明 static int free; // 静态成员声明 int Start, Finish; // 多项式的起、始位置 其中,MaxTerms是常数。由于类中的静态成员声明不构成其定义,还必须在类定义之外定义静态成员如下: term Polynomial::termArray[MaxTerms]; int Polynomial::free = 0; // 指示termArray中的下一个可用单元 ;例如,A(x) = 2x800+3x3+1和B(x) = 7x5+x3+5x+2;2.2.2 多项式相加 ; 9 case ‘: NewTerm(termArray[b].coef, termArray[b].exp); 10 b++; 11 break; 12 case ‘: NewTerm(termA

文档评论(0)

1亿VIP精品文档

相关文档