线性表的顺序表示是用一组地址连续的存储单元依次存储线性表中的元素。这样,逻辑上相邻的元素在物理上(存储空间)也相邻。
#include "LinearList.h"
using namespace std;
template <class T>
class SeqList : public LinearList<T>
{
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;
private:
int maxLength; //顺序表的最大长度
T *element; //动态一维数组指针
};
template <class T>
SeqList<T>::SeqList(int mSize)
{
maxLength = mSize;
element = new T[maxLength];
n = 0;
}
template <class T>
SeqList<T>::~SeqList()
{
delete [] element;
}
/*
*Is Empty?
*/
template <class T>
bool SeqList<T>::IsEmpty() const
{
return n == 0;
}
/*
*The length
*/
template <class T>
int SeqList<T>::Length() const
{
return n;
}
/*
*Find the element[i]
*If it exits, x = element[i] and return true,
*else return false
*/
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 = element[i];
return true;
}
/*
*Search element x
*exit: return the index
*else:return -1
*/
template <class T>
int SeqList<T>::Search(T x) const
{
for(int i=0; i<n; i++)
{
if (element[i] == x)
{
return i;
}
}
return -1;
}
/*
*Insert x in element[i+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--)
{
element[j+1] = element[j];
}
element[i+1] = x;
n ++;
return true;
}
/*
*Delete element[i]
*/
template <class T>
bool SeqList<T>::Delete(int i)
{
if(IsEmpty())
{
cout<<"Underflow"<<endl;
return false;
}
if(i<0 || i>n-1)
{
cout<<"Out of Bounds"<<endl;
return false;
}
for(int j=i; j<n-1; j++)
{
element[j] = element[j+1];
}
n --;
return true;
}
/*
*Update element[i]
*/
template <class T>
bool SeqList<T>::Update(int i, T x)
{
if(i<0||i>n-1)
{
cout <<"Out of Bounds"<<endl;
return false;
}
element[i] = x;
return true;
}
/*
*Output
*/
template <class T>
void SeqList<T>::Output(ostream &out) const
{
for(int i=0; i<n; i++)
{
out <<element[i]<<" ";
}
out << endl;
}
未完待续。。。
---------------------------------------------------------------------------------------------------------------------------------------
不是每一次努力都会有收获,但是,每一次收获都必须努力,这是一个不公平的不可逆转的命题 。