// List.cpp : 定义控制台应用程序的入口点。#include "stdafx.h"#includeusing namespace std;/**线性表的C++抽象类声明*/template class List{public:virtual void clear() = 0;//清除virtual bool insert(const Elem&) = 0;//插入virtual bool append(const Elem&) = 0;//添加在线性表的表尾virtual bool remove(const Elem&) = 0;//删除一个元素virtual void setStart() = 0;//设置表头virtual void setEnd() = 0;//设置表尾virtual void prev() = 0;//求一个元素的前驱virtual void next() = 0;//求一个元素的后继virtual int leftLength() = 0;//求栅栏左边元素的长度virtual int rightLength() = 0;//求栅栏右边元素的长度virtual bool setPos(int pos) = 0;//确定元素在线性表中的位置virtual bool getValue(Elem&) const= 0;//求元素的参数值virtual void print() = 0;//打印};template //顺序表的实现class AList :public List{//AList继承抽象类List因此它实现List的所有成员函数private:int maxSize;//线性表的最大存储量int listSize;//声明线性表的长度int fence;//声明栅栏Elem* listArray;//声明一个容纳顺序表元素的数组public:AList(int size = DefaultListSize){//构造函数maxSize = size;listSize = fence = 0;listArray = new Elem[maxSize];}~AList(){//析构函数delete[] listArray;}void clear(){delete[] listArray;listSize = fence = 0;liatArray = new Elem[maxSize];}bool insert(const Elem&);bool append(const Elem&);bool remove(Elem&);void setStart(){fence = 0;}void setEnd(){fence = listSize;}void prev(){if (fence != 0) fence--;}void next(){if (fence <= listSize) fence++;}int leftLength() const{return fence; }int rightLength() const{return listSize - fence;}bool setPos(int pos){if ((pos >= 0) && (pos <= listSize)) fence = pos;return (pos >= 0) && (pos <= listSize);}bool getValue(Elem & it){if (rightLength() == 0) return false;else{it = listArray[fence];return true}}void print() const{int temp = 0;cout << "< ";while (temp < fence) cout << listArray[temp++] << " ";cout << " | ";while (temp < listSize) cout << listArray[temp++] << " ";cout << ">\n";}};template bool AList::insert(const Elem& item){if (listSize == maxSize) return false;//如果线性表达到最大长度,不允许插入for (int i = listSize; i>fence; i--)//从表尾开始遍历listArray[i] = listArray[i - 1];//第i-1的元素移到第i位listArray[fence] = item;//把要插入的元素插入到fence的位置listSize++;return true;}template bool AList::append(const Elem& item){if (listSize == maxSize) return false;listArray[listSize++] = item;//把要添加的元素添加到表尾return true;}template bool AList::remove(Elem& item){if (rightLength == 0) return false;item = listArray[fence];for (int i = fence; i < listSize - 1; i++){listArray[i] = listArray[i + 1];listSize--;return true;}}int _tmain(int argc, _TCHAR* argv[]){AList aList;return 0;}
C++实现线性表之顺序表
最新推荐文章于 2022-11-10 20:31:54 发布