数据结构学习 C++实现简单的线性表
模版定义头文件linear.h
#include <iostream>
using namespace std;
template<class type>
class LiList
{
public:
LiList(int maxLength = 20);
~LiList();
bool isEmpty() const { return length==0;}
int getLength() const;
bool getValue(int index,type & x) const; //得到index处的值,将其存在x,index从1开始
int getIndex(const type &t) const; //查找t所在位置,没有t怎返回-1
void print(ostream& out) const; //打印线性表
LiList<type>& delElement(int index,type &x); //删除index处的元素,并将其值返回到x中
LiList<type>& insertElement(int index,const type&x); //在index元素之后插入x
void push(const type&x); //在线性表的最后插入一个元素
private:
int length;
int MaxSize;
type *element;
};
template<class type>
LiList<type>::LiList(int maxLength)
{
length=0;
MaxSize=maxLength;
element = new type[MaxSize];
}
template<class type>
LiList<type>::~LiList()
{
delete[]element;
element = NULL;
}
template<class type>
bool LiList<type>::getValue(int index,type & x) const
{
if(index <1 || index>length) return false;
x = element[index - 1];
return true;
}
template<class type>
int LiList<type>::getIndex(const type &t) const
{
for(int i = 0;i<length;i++)
{
if(element[i] == t)return ++i;
}
return -1;
}
template<class type>
void LiList<type>::print(ostream & out) const
{
out<<"length:" << length<<endl;
for (int i = 0; i < length; i++)
{
out<<"element "<<i<<": "<<element[i]<<endl;
}
}
template<class type>
LiList<type> & LiList<type>::delElement(int index,type &x)
{
x = element[index - 1];
for(int i = index;i<length;i++)
{
element[i-1]=element[i];
}
length--;
return *this;
}
template<class type>
LiList<type>& LiList<type>::insertElement(int index,const type&x)
{
if(length>=MaxSize) return *this;
if(index <1 || index >length) return *this;
for(int i = length ; i>index;i--)
{
element[i] = element[i-1];
}
length++;
element[index]=x;
return *this;
}
template<class type>
void LiList<type>::push(const type&t)
{
if(length == MaxSize)return;
length++;
element[length-1] = t;
}
template<class type>
int LiList<type>::getLength() const
{
return length;
}
测试用的代码
#include "linear.h"
#include "time.h"
#include <cstdlib>
int main()
{
LiList<int> intList(10);
srand((unsigned)time(NULL));
cout<<"length:"<<intList.getLength()<<endl;
int z=0,y=0;
for(int i = 0 ;i<10;i++)
{
z=(int)rand()%9999;
intList.push(z);
}
intList.print(cout);
cin>>z;
cout<<intList.getIndex(z)<<endl;
cout<<"delete one element(input the index):"<<endl;
cin>>z;
intList.delElement(z,y);
intList.print(cout);
cout<<"insert one element(input the index):"<<endl;
cin>>z;
intList.insertElement(z,y);
intList.print(cout);
system("pause");
exit(EXIT_SUCCESS);
}