- 逻辑上相邻的元素,物理上也相邻
- 逻辑位序和物理位序相差1
- 预定义的常量
#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef char ElemType;
- 顺序表的定义
静态存储:
#define MAXSIZE 100 typedef struct{ ElemType elem[MAXSIZE]; int length; }SqList;
动态存储:
typedef struct{ ElemType *elem; int length; }SqList; L.elem = new ElemType(MAXSIZE);//或者 L.elem = (ElemType*)malloc(sizeof(ElemType)*MAXSIZE);
- 线性表L的初始化
Status InitList_Sq(SqList &L){
L.elem = new ElemType[MAXSIZE];
if(!L.elem)exit(OVERFLOW);//存储分配失败
L.length = 0;
return OK;
}
6.销毁线性表L
void DestroyList(SqList &L){
if(L.elem)
delete L.elem;//释放存储空间
}
7.清空线性表L
void ClearList(SqList &L){
L.length = 0;
}
8.求线性表的长度
int Getlength(SqList L){
return (L.length);
}
9.判断线性表L是否为空
int IsEmpty(SqList L){
if(L.length == 0)return 1;
else return 0;
}
10.顺序表的取值
时间复杂度O(1)
int GetElem(SqList L, int i, ElemType &e){
if(i<1||i>L.length)return ERROR;//判断i值是否合理
e=L.elem[i-1];//第i-1的单元存储着第i个元素
return OK;
}
11.线性表的查找
顺序查找
ASL(Average Search Length)每个元素的查找次数之和除以元素的个数。
int LocateElem(SqList L,ElemType e){
for(i=0;i<L.length;i++)
if(L.elem[i]==e)return i+1;//查找成功,返回序号
return 0;
}
12.线性表的插入
插入位置:
1.最后 2.中间 3.最前面
Status ListInsert_Sq(SqList &L, int i, ElemType e){
if(i<1||i>L.length+1)
return ERROR;
if(L.length == MAXSIZE)
return ERROR;
for(j = L.length - 1;j >= i-1;j--)
L.elem[j+1] = L.elem[j]; //遍历整个表,移动之后每一个元素
L.elem[i-1] = e; //将e放入第i个位置
L.length++;
return OK;
}
13.线性表的删除
时间复杂度O(n)
Status ListDelete_Sq(SqList &L, int i){
if((i<1)||(i>length))
return ERROR;
for(j=i;j<L.length-1;j++)
L.elem[j-1]=L.elem[j];
L.length--;
return OK;
}