数据结构-线性表 (C++)

#include
using namespace std;


const int DefaultSize=100;//默认线性表大小


template<class T>
class LinearList
{
public:
LinearList(int MaxListSize = DefaultSize);
~LinearList() 
{
delete [] elements;
}
bool IsEmpty() const          //判断是否为空
{
return length == 0;
}
bool IsFull() const           //判断是否为满
{
return length == MaxSize;
}
int Length() const           //获取线性表当前长度
{
return length;
}
int Find(T x) const;        //查找线性表中第一个值为x的元素,返回该元素在数组中位置下标,如若不存在返回-1
bool Delete(T x);           //删除线性表中第一个值为x的元素,如若不存在返回false
bool Insert(int k,T x);     //在数组下标k处插入值为x的元素,失败则返回false
T Get(int i)                //返回线性表下标为i的值,如若不存在返回0
{
if(i<0||i>length-1)
{
cout<<"Input Error!"<<endl;
   return 0;
}
return elements[i];
}
    void Print();              //打印数组元素


private:
int length;                 //当前线性表长度,无元素长度为0
int MaxSize;                //线性表最大长度
T* elements;                //存储线性表元素




};


template<class T>
LinearList<T>::LinearList(int MaxListSize)
{
MaxSize = MaxListSize;
if(MaxSize>0)
elements = new T[MaxSize];
length = 0;
}


template<class T>
int LinearList<T>::Find(T x) const
{
    for(int i=0;i<length;i++)
{
if(elements[i]==x)
return i;
}
cout<<"Can not find the element you want !"<<endl;
return -1;


}
template<class T>
bool  LinearList<T>::Delete(T x)
{
for(int i=0;i<length;i++)
{
if(elements[i]==x)
{
for(int j=i;j<length-1;j++)
{
elements[j]=elements[j+1];
}
length--;
return true;
}
}
cout<<"the element does not exist!";
return false;
}


template<class T>
bool  LinearList<T>::Insert(int k,T x)
{
if(k<0||k>length||length>=MaxSize)
{
cout<<"Can not Insert!"<<endl;
return false;
}
else
{
for(int j=length;j>k;j--)
{
elements[j] = elements[j-1];
}
elements[k] = x;
length++;
return true;
}


}




template<class T>
void  LinearList<T>::Print(){
for(int i=1;i<=length;i++)
cout<<i<<":\t"<<elements[i-1]<<endl;
cout<<endl<<endl;
}














int main()
{
LinearList<int> test(15);
int array[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
for(int i=0;i<15;i++)
{
test.Insert(i,array[i]);
    }


test.Print();
int position = test.Find(7);
cout<<"First position:  "<<position<<endl;
test.Delete(2);
cout<<"After Delete:"<<endl;
test.Print();
test.Insert(7,777);
cout<<"After Insert:"<<endl;
test.Print();
system("pause");
return 0;






}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章