顺序表基础操作的实现
#include<iostream>
using namespace std;
//函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXSIZE 100 //线性表存储空间的初始分配量
//Status 是函数的类型,其值是函数结果状态代码
typedef int Status;
typedef char ElemType;
//顺序表类型定义
typedef struct{
ElemType *elem;
int length; //当前长度
}SqList;
//构造一个空的顺序表L
Status InitList(SqList &L){
L.elem = new ElemType[MAXSIZE]; //分配空间
if(!L.elem) exit(OVERFLOW); //存储分配失败
L.length = 0; //空表长度为0
return OK;
}
//销毁线性表
void DestoryList(SqList &L){
if(L.elem)delete L.elem; //释放存储空间
}
//清空线性表
void ClearList(SqList &L){
L.length = 0; //将线性表长度置为0
}
//求线性表L的长度
int GetLength(SqList &L){
return (L.length);
}
//判断线性表是否为空
int IsEmpty(SqList &L){
if(L.length == 0)return 1;
else return 0;
}
//获取位置i相应位置数据元素的内容
int GetElem(SqList &L,int i,ElemType e){
if(i < 1 || i > L.length)return ERROR;
//判断i值是否合理,若不合理,返回ERROR
e = L.elem[i-1]; //第i-1的单元存储着第i个数据
return OK;
}
//在线性表中查找值为e的数据元素,返回其序号
int LocateElem(SqList &L,ElemType e){
for(int i = 0; i < L.length; i++){
if(L.elem[i] == e)return i+1; //查找成功,返回序号
}
return 0; //查找失败,返回0
}
Status ListInsert_Sq(SqList &L,int i,ElemType e){
if(i>L.length+1 || i < 1)return ERROR; //i值不合法
if(L.length == MAXSIZE)return ERROR; //当前存储空间已满
for(int j = L.length - 1; j >= 1; j--){
L.elem[j+1] = L.elem[j]; //插入位置及之后的位置后移
}
L.elem[i-1] = e;
L.length++;
return OK;
}
Status DeleteList(SqList &L,int i){
if(i > L.length || i < 1)return ERROR;
for(int j = i; j < L.length -1; j++){
L.elem[j-1] = L.elem[j];
}
L.length--;
return OK;
}
int main(){
return 0;
}
平均查找长度ASL(Average Search Length):
对于有n个记录的表
* 未确定记录在表中的位置。需要与给定值进行比较的关键字的个数的期望值*叫做查找算法的平均查找长度。
* ASL = P1+P2+...+(n-1)Pn-1 = (n+1)/2
顺序表优缺点
- 优点
- 存储密度大(结点本身所占存储量/结点结构所占存储量)
- 可以随机存储表中任一元素
- 缺点
- 再插入,删除时,需要移动大量元素
- 浪费存储空间
- 属于静态存储形式,数据元素的个数不能自由扩充
关于如何克服这一缺点,需要由线性表的链式表示来克服.线性表的链式表示,我会随后更新......