數據結構-線性表 (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;






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