您的位置:首页 > 理论基础 > 数据结构算法

数据结构-线性表-顺序表示 (二)

2011-09-24 15:47 274 查看
线性表的顺序表示(二):


头文件:seqlist.h


#include "linearlist.h"

template <class T>
class SeqList:public LinearList<T>
{
private:
int maxLength;	// 顺序表的最大长度
T *elements;	// 动态一维数组的指针

public:
SeqList(int mSize);
~SeqList();
bool IsEmpty() const;
int Length() const;
bool Find(int i, T &x) const;
int Search(T x) const;
bool Insert(int i, T x);
bool Delete(int i);
bool Update(int i, T x);
void Output(ostream &out) const;
};

template <class T>
SeqList<T>::SeqList(int mSize)
{
maxLength = mSize;
elements = new T[maxLength];
n = 0;
}

template <class T>
SeqList<T>::~SeqList()
{
delete[] elements;
}

template <class T>
bool SeqList<T>::IsEmpty() const
{
return n == 0;
}

template <class T>
int SeqList<T>::Length() const
{
return n;
}

template <class T>
bool SeqList<T>::Find(int i, T &x) const
{
if (i < 0 || i > n-1) {
cout << "Out of Bounds"<<endl;
return false;
}
x = elements[i];
return true;
}

template <class T>
int SeqList<T>::Search(T x) const
{
for(int i = 0; i < n; i++ ) {
if(elements[i] == x) {
return i;
}
}
return -1;
}

template <class T>
bool SeqList<T>::Insert(int i, T x)
{
if(i < -1 || i > n-1) {
cout<<"Out Of Bounds"<<endl;
return false;
}

if(n == maxLength) {
cout<<"OverFlow"<<endl;
return false;
}

for( int j = n-1; j>i; j--) {
elements[j+1] = elements[j];
}
elements[i+1] = x;
n++;
return true;
}

template <class T>
bool SeqList<T>::Delete(int i)
{
if(n == 0) {
cout << "UnderFlow" <<endl;
return false;
}

if(i < -1 || i > n-1) {
cout<<"Out Of Bounds"<<endl;
return false;
}

for( int j = i + 1; j < n; j++) {
elements[j-1] = elements[j];
}

n--;
return true;
}

template <class T>
bool SeqList<T>::Update(int i, T x)
{
if(i < -1 || i > n-1) {
cout<<"Out Of Bounds"<<endl;
return false;
}

elements[i] = x;
return true;
}

template <class T>
void SeqList<T>::Output(ostream &out) const
{
for(int i = 0; i < n; i++ ) {
out << elements[i];
if(i != n-1) {
out<<" ";
}
}
out << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: