线性表Linearlist

时间:2023-03-08 16:21:32

顺序存储,链式存储,索引存储,散列存储

基本运算

SLIST

       
1.置空表 void SetNull(&L)    
2.求长度 int Length(L)    
3.取元素 ElemType Get(L,i) 取第i个位置的元素  
4.取前驱 ElemType Prior(L,x) 取元素值x的直接前驱  
5.取后继 ElemType Next(L,x) 取元素值x的直接后继  
6.定位函数 int Locate(L,x) 查找值为x的位置  
7.插入 void Insert(&L,x,i) 在第i个位置插入值为x的元素  
8.删除 void Dele(&L,i) 删除第i个位置上的元素  

顺序存储:

const int M=Maxlen;//线性表的最大长度
class Sequenlist
{
public :
elemtype a[M];
int len; int length(sequenlist L); void Insert(sequenlist &L,elemtype x,int i);
void Dele(sequenlist &L,int i);
void SetNull(sequenlist &L); int Locate(sequenlist L,elemtype x);
elemtype Get(sequenlist L,int i);
elemtype Prior(sequenlist L,elemtype x);
elemtype Next(sequenlist L,elemtype x);
} //求长度
int sequenlist::length(sequenlist L)
return L.len;
//置空
void sequenlist ::SetNull(sequenlist &L)
L.len=0; //取元素
elemtype sequenlist::Get(sequenlist L,int i)
{
if((i<0)||(i>L.len))
return NULL:
else
return L.a[i];
}
//定位
int sequenlist::Locate(sequenlist L,elemtype x)
{
int i=0;
while((i<L.len)&&(L.a[i]!=x))
i++;
if(i<L.len) return i;
else return -1;
} //插入
//1、超过表长,溢出,不能插入
//2、i值非法,不能插入 void sequenlsit::Inset(sequenlist &L,elemtype x,int i)
{
int j;
if(L.len>=M-1)
cout<<"overflow"<endl;
else if((i<1)||(i>L.len+1))
cout<<"position is not correct"<<endl;
else{
for(j=L.len;i>=i;j—)
L.a[j+1]=L.a[j]; //元素后移
L.a[i]=x;//插入元素
L.len++;//表长加1
}
} //删除
void sequenlist ::Dele(sequenlist &L,int i)
{
int j;
if((i<1)||(i>L.len+1))
cout<<"position is not correct"<<endl;
else{
for(j=i+1;j<=L.len:j++)
L.a[j-1]=L.a[j];//元素前移覆盖
L.len--;
}
}
//动态分配,指针
class sequenlist
{
public:
elemtype *a;
int len;
...
}
//置空需要修改
void sequenlist::SetNull(sequenlist &L)
{ L.a=new elemtype[M];//动态申请存储单元
if(L.a==NULL) exit(1);//申请失败
L.len=0;
}