一、顺序表示
- 顺序存储:把逻辑上相邻的数据元素存储在物理相邻的存储单元中
- 用一维数组表示
//一、数组静态分配
#define MAXSIZE 100
typedef struct{
...
}ElemType;
typedef struct{
ElemType elem[MAXSIZE];
int length;//顺序表的长度
}SqList;//Sequence List顺序表
//二、数组动态分配
#include<cstdlib>
#define MAXSIZE 100
typedef struct{
...
}ElemType;
typedef struct{
ElemType *elem;
int length;
}SqList;
SqList L;
//强制类型转换 //乘
L.elem=(ElemType*)malloc(sizeof(ElemType)*MAXSIZ);
//malloc(m) 开辟m字节长度的地址空间,并返回这段空间的首地址
//头文件为<cstdlib>
二、基本操作实现
基本操作:
实现:
#include<iostream>
#include<cstdlib>
#define MAXSIZE 100//线性表储存空间的最大初始分配量
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1//infeasible 不可实行的
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;
typedef struct{
ElemType *elem;//储存空间基址
int length;//当前长度
}SqList; //顺序表
//引用
Status InitList(SqList &L){
//构造线性表
L.elem=new ElemType[MAXSIZE];
//或L.elem = (ElemType*)malloc(MAXSIZE*sizeof(ElemType));
if(!L.elem) exit(OVERFLOW);//储存分配失败 exit()中断程序执行 在iostream和cstdlib头文件中声明
L.length = 0;
return OK;
}
Status DestroyList(SqList &L){
//销毁线性表
//或free(L.elem);//free(p) 释放指针p所指变量的存储空间,即彻底删除该变量 在cstdlib头文件中声明
delete L.elem;//释放存储空间
return OK;
}
Status ClearList(SqList &L){
//将L置为空表
L.length=0;
return OK;
}
Status ListEmpty(SqList L){
//判断线性表是否为空
if(!L.elem)
return FALSE;
else
return TRUE;
}
Status ListLength(SqList L){
//计算线性表的长度
return L.length;
}
//取值
Status GetElem(SqList L,int i,ElemType &e){
if(i<1||i>L.length)
return ERROR;
e=L.elem[i-1];
return OK;
}
//前驱
Status PriorElem(SqList L,ElemType cur_e,ElemType &pre_e){
int i;
for(i=0;i<L.length;i++){
if(cur_e==L.elem[0]){
return FALSE;
}
else if(cur_e==L.elem[i]){
pre_e=L.elem[i-1];
return TRUE;
}
}
return FALSE;
}
//后继
Status NextElem(SqList L,ElemType cur_e,ElemType &next_e){
int i;
for(i=0;i<L.length;i++){
if(cur_e==L.elem[L.length]){
return FALSE;
}
else if(cur_e==L.elem[i]){
next_e=L.elem[i+1];
return TRUE;
}
}
return FALSE;
}
//查找 查找与e一样的数据元素,成功返回位置序号,失败返回0
int LocateElem(SqList L,ElemType e){
for(int i=0;i<L.length;i++)
if(L.elem[i]==e) return i+1;
return 0;
}
//插入
Status ListInsert(SqList &L,int i,ElemType e){
if(i>0&&i<L.length+2){
L.length++;
if(L.length>MAXSIZE)return ERROR;
for(int j=L.length-2;j>i;j--){
L.elem[j+1]=L.elem[j];//后移
}
L.elem[i-1]=e;
}
return OK;
}
else return ERROR;
}
//删除
Status ListDelete(SqList &L,int i,ElemType &e){
if((i<1)||(i>L.length)) return ERROR;
for(int j=i;j<=L.length;j++)
L.elem[j-1]=L.elem[j];//被删除元素之后的元素前移
L.length--;
return OK;
}
int main(){
......
}
三、算法分析
查找
- 平均查找长度ASL(Average Search Length)
- 为确定记录在表中的位置,需要与给定值进行比较的关键字的个数的期望值叫作算法的平均查找长度
- 平均时间复杂度为O(n)
- 空间复杂度为O(1)
插入
- 平均时间复杂度为O(n)
- 空间复杂度为O(1)
删除
- 平均时间复杂度为O(n)
- 空间复杂度为O(1)
四、顺序表优缺点
优点
- 存储密度大,为1(结点本身所占存储量/结点结构所占存储量)
- 可以随机存取表中任一元素
缺点
- 在插入、删除某一元素时,需要移动大量元素
- 浪费存储空间
- 属于静态存储形式,数据元素的个数不能自由扩充