声明
class seqlist{
private:
int length;//长度
int data[Maxsize];//数据域
public:
seqlist();//无参构造函数
seqlist(int a[],int n);//有参构造函数
~seqlist(){};//析构函数,可写可不写
int Length();//获得长度
int Get(int i);//按位获取
int Locate(int x);//按值获取,返回位置
void Insert(int x,int i);//插入函数
int Delete(int i);//删除函数,返回删除的值
int Empty();//判空函数,为空返回0,不为空返回1
void printlist();//输出函数
};
实现
#include <iostream>
using namespace std;
const int Maxsize=100;
class seqlist{
private:
int length;
int data[Maxsize];
public:
seqlist();
seqlist(int a[],int n);
~seqlist(){};
int Length();
int Get(int i);
int Locate(int x);
void Insert(int x,int i);
int Delete(int i);
int Empty();
void printlist();
};
seqlist::seqlist(){
length=0;
}
seqlist::seqlist(int a[],int n){
if(n>Maxsize)cout<<"参数非法"<<endl;
else {
for(int i=0;i<n;i++){
data[i]=a[i];
}
length=n;
}
}
int seqlist:: Length(){
return length;
}
int seqlist:: Get(int i){
if(i>length||i<1)throw "参数错误";
return data[i-1];
}
int seqlist:: Locate(int x){
for(int i=0;i<length;i++){
if(data[i]==x){
return i+1;
}
}
}
void seqlist:: Insert(int x,int i){
if(length==Maxsize)throw "线性表数据已满";
if(i>length||i<1)throw "插入位置错误";
for(int j=length;j>=i;j--){
data[j]=data[j-1];
}
data[i-1]=x;
length++;
}
int seqlist::Delete(int i){
if(length==0)throw "表中没有数据";
if(i>length||i<1)throw "删除位置错误";
int ans=data[i-1];
for(int j=i-1;j<length-1;j++){
data[j]=data[j+1];
}
length--;
return ans;
}
int seqlist:: Empty(){
if(length==0)return 0;
else return length;
}
void seqlist::printlist(){
if(length==0)throw "表内没有数据";
for(int i=0;i<length;i++){
cout<<data[i]<<" ";
}
cout<<endl;
}
int main()
{ int a[5]={1,2,3,4,5};
seqlist list1(a,5);
try
{
list1.printlist();
cout<<list1.Length()<<endl;
cout<<list1.Get(1)<<endl;
cout<<list1.Locate(2)<<endl;
cout<<list1.Delete(1)<<endl;
list1.printlist();
}catch(const char *e){
cout<<e<<endl;
}
return 0;
}
想法
顺序表的优势在于实现起来很方便,按位查找很快,在知道具体空间时很方便。缺点就是,在插入和删除时需要移动很多元素,不容易扩展空间,在不知道需要的空间大小时容易造成数组空间浪费。