线性表是一种存储的数据结构,可以作为动态数组存储数据,下面是C++的线性表的类定义
#include <iostream>
#include <stdlib.h>
using std::cout;
using std::cin;
using std::endl;
//线性表类
class LinearList
{
private:
int MaxSize;
int length;
int* element;
public:
//带一参的构造函数,设置最大长度
LinearList(int Max)
{
MaxSize=Max;
length=0;
element=new int[Max];}
//无参的时候,长度默认为5
LinearList()
{
MaxSize=5;
length=0;
element=new int[5];
}
//判断是否为空的函数
bool isEmpty()
{
int* prt=element;
int count=0;
for(int i=0;i<MaxSize;i++)
{
//不为空的时候执行
if(*prt!=NULL)
{
count++;
}
}
if(count!=0)
return false;
else
return true;
}
int getLength()const
{
return length;
}
//返回第k个元素至x中
bool Find(int k,int& x)
{
if(k>length && k<0)
return false;
else
{
x=element[k];
return true;
}
}
//搜索元素返回下表x
int Search(const int &x)const
{
for(int i=0;i<length;i++)
{
if(element[i]==x)
return i;
}
return -1;
}
//删除操作
LinearList& Delete(int k,int &x)
{
if(k<length && k>0)
{
x=element[k];
for(int i=k;i<length-1;i++)
{
element[k]=element[k+1];
}
length--;
}
else
{
cout<<"the element does not exist!"
<<endl;
}
return *this;
}
//重新设置Max
LinearList& reSet(int Max)
{
int *elements;
if(Max>MaxSize)
{
elements=new int[Max];
for(int i=0;i<length;i++)
{
elements[i]=element[i];
}
element=elements;
delete[] elements;
return *this;
}
else
{
cout<<"error,can not reset!"
<<endl;
return *this;
}
}
//插入x到第k个位置
LinearList& Insert(int k,const int& x )
{
if(k<0 && k>length)
{
cout<<"Ouf of Bounds"
<<endl;
exit(1);
}
else
{
element[k]=x;
length++;
}
return *this;
}
~LinearList()
{
delete[] element;
}
void OutPut()
{
for(int i=0;i<length;i++)
{
cout<<element[i]<<" ";
}
cout<<endl;
}
};
//线性表测试
int main(void)
{
LinearList list(10);
cout<<list.isEmpty()<<endl;
list.Insert(0,0);
list.Insert(1,1);
list.Insert(2,2);
list.OutPut();
int x;
list.Delete(1,x);
cout<<x
<<endl;
list.OutPut();
}