结点的变体(异质数据) 25 3.3 62 74 1.0 63 ·若想在线性表中存放不同类型的数据,可采用等价 定义union: typedef union int val; /按data.val引用 char ch; /按data.ch引用 float dir; 按data.dir引用 union data*link;/按data.link引用 data; /整体上是同一类型data 6
6 结点的变体(异质数据) • 若想在线性表中存放不同类型的数据,可采用等价 定义union: typedef union { int val; //按data.val引用 char ch; //按data.ch引用 float dir; //按data.dir引用 union data *link; //按data.link引用 } data; //整体上是同一类型data 25 ‘s’ 3.3 62 74 ‘t’ 1.0 ‘6’
顺序表(SeqList)类的定义 #include <iostream.h> /定义在“seq List..h”中 #include <stdlib.h> #include "linearList.h" const int defaultSize 100; template class E> class SeqList:public LinearList<E> protected; E *data; /存放数组 int maxSize; 川最大可容纳表项的项数 int last; /当前已存表项的最后位置 void reSize(int newSize);/改变数组空间大小
7 顺序表(SeqList)类的定义 #include <iostream.h> //定义在“seqList.h”中 #include <stdlib.h> #include “linearList.h" const int defaultSize = 100; template < class E> class SeqList: public LinearList<E> { protected: E *data; //存放数组 int maxSize; //最大可容纳表项的项数 int last; //当前已存表项的最后位置 void reSize(int newSize); //改变数组空间大小
public; SeqList(int sz defaultSize); /构造函数 SeqList(SeqList<E>&L); /复制构造函数 SeqListO delete]data;} /析构函数 int Size()const {return maxSize;} 川求表最大容量 int Length()const {return last+1;} 计算表长度 int Search(E&x)const; /搜索X在表中位置,数返回表项序号 int Locate(int i)const; /定位第个表项,函数返回表项序号 bool getData(inti,E&x)const,:/取第i个表项的值 bool Insert(int i,E x); /插入 bool Remove(int i,E&x); /删除 }; 8
8 public: SeqList(int sz = defaultSize); //构造函数 SeqList(SeqList<E>& L); //复制构造函数 ~SeqList() {delete[ ] data;} //析构函数 int Size() const {return maxSize;} //求表最大容量 int Length() const {return last+1;} //计算表长度 int Search(E& x) const; //搜索x在表中位置,函数返回表项序号 int Locate(int i) const; //定位第 i 个表项,函数返回表项序号 bool getData(int i, E& x) const; //取第i个表项的值 bool Insert(int i, E x); //插入 bool Remove(int i, E& x); //删除 };
顺序表的构造函数 #include <stdlib.h> /操作《exit”存放在此 #include“seqList..h” /操作实现放在《seqList..cpp” template <class E> SeqList<E>::SeqList(int sz){ if (SZ>0 maxSize sz;last =-1; data new E[maxSizel; /创建表存储数组 if(data==NULL){∥动态分配失败 cerr<<"存储分配错误!"<<end; exit(1); }; 9
9 顺序表的构造函数 #include <stdlib.h> //操作“exit”存放在此 #include “seqList.h” //操作实现放在“seqList.cpp” template <class E> SeqList<E>::SeqList(int sz) { if (sz > 0) { maxSize = sz; last = -1; data = new E[maxSize]; //创建表存储数组 if (data == NULL){ //动态分配失败 cerr << "存储分配错误!" << endl; exit(1); } } };
复制构造逐数 template <class E> SeqList<E>:SeqList SeqList<E>&L) maxSize L.Size(;last L.Length()-1; E value; data new E[maxSize]; /创建存储数组 if (data ==NULL) 川动态分配失败 {cerr<<"存储分配错误!"<<end; exit(1); for(inti=l;i<=last+l;i++)/传送各个表项 L.getData(i,value);data[i-1]value; }; 10
10 template <class E> SeqList<E>::SeqList ( SeqList<E>& L ) { maxSize = L.Size(); last = L.Length()-1; E value; data = new E[maxSize]; //创建存储数组 if (data == NULL) //动态分配失败 {cerr << "存储分配错误!" << endl; exit(1);} for (int i = 1; i <= last+1; i++) //传送各个表项 {L.getData(i, value); data[i-1] = value;} }; 复制构造函数