用c++模板实现 线性表(数组表示)
Code
#include <iostream>
#include <string>
using namespace std;
template <typename T> class LinearList{
public:
LinearList();
LinearList(int num);
T * insert(int index,T value);
T delVal(int index);
int GetLength(){return length;}
bool isEmpty(){return length==0;}
bool isElem(T value,int &index)
{
for (int i=0;i<length;++i)
{
if(vec[i]==value)
{
index=i;
return true;
}
}
return false;
}
T & GetElem(int index)
{
return vec[index];
}
private:
int length;
int capicity;
T *vec;
};
template <typename T> LinearList<T>::LinearList()
{
capicity=100;
length=0;
vec=new T[capicity];
}
template <typename T> LinearList<T>::LinearList(int num)
{
if(num<0)
exit(OVERFLOW);
capicity=num;
length=0;
vec=new T[capicity];
}
template <typename T> T * LinearList<T>::insert(int index, T value)
{
if(index<0||index>length)
cout<<"overflow"<<endl;
if(length>=capicity)
{
T *newVec=new T[capicity*2];
for (int i=0;i<length;++i)
{
newVec[i]=vec[i];
}
delete [] vec;
vec=newVec;
capicity*=2;
}
T *beg=&vec[index];
for (T *end=&vec[length-1];end>=beg;--end)
{
*(end+1)=*end;
}
*beg=value;
++length;
return beg;
}
template <typename T> T LinearList<T>::delVal(int index)
{
if (index<0||index>length)
{
cout<<"overflow"<<endl;;
}
T *temp=&vec[index];
T ret=*temp;
for(T *end=&vec[length-1];temp<=end;++temp)
*temp=*(temp+1);
--length;
return ret;
}
#include <iostream>
#include <string>
using namespace std;
template <typename T> class LinearList{
public:
LinearList();
LinearList(int num);
T * insert(int index,T value);
T delVal(int index);
int GetLength(){return length;}
bool isEmpty(){return length==0;}
bool isElem(T value,int &index)
{
for (int i=0;i<length;++i)
{
if(vec[i]==value)
{
index=i;
return true;
}
}
return false;
}
T & GetElem(int index)
{
return vec[index];
}
private:
int length;
int capicity;
T *vec;
};
template <typename T> LinearList<T>::LinearList()
{
capicity=100;
length=0;
vec=new T[capicity];
}
template <typename T> LinearList<T>::LinearList(int num)
{
if(num<0)
exit(OVERFLOW);
capicity=num;
length=0;
vec=new T[capicity];
}
template <typename T> T * LinearList<T>::insert(int index, T value)
{
if(index<0||index>length)
cout<<"overflow"<<endl;
if(length>=capicity)
{
T *newVec=new T[capicity*2];
for (int i=0;i<length;++i)
{
newVec[i]=vec[i];
}
delete [] vec;
vec=newVec;
capicity*=2;
}
T *beg=&vec[index];
for (T *end=&vec[length-1];end>=beg;--end)
{
*(end+1)=*end;
}
*beg=value;
++length;
return beg;
}
template <typename T> T LinearList<T>::delVal(int index)
{
if (index<0||index>length)
{
cout<<"overflow"<<endl;;
}
T *temp=&vec[index];
T ret=*temp;
for(T *end=&vec[length-1];temp<=end;++temp)
*temp=*(temp+1);
--length;
return ret;
}