2-4 线性表的顺序表示和实现(3)

注意:存储单位逻辑位序和物理位序差1(数组的第一个元素index为0)

顺序表示意图:

L.length=n

补充:算法中用到的常量和类型

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
//Status是函数的类型,其值是函数结果状态代码
typedef int Status;
typedef char ElemType;

简易算法

(1)线性表L的初始化

Status Init_Sq(SqList &L) { //创建一个空的顺序表L
	L.elem = new ElemType[MAXSIZE}; //为L分配空间
	if(!L.elem) { //存储空间分配失败。如果L.elem为空,结果为false。那么!L.elemt就为true
		exit(OVERFLOW);
	}
	L.length = 0; //空表长度为0
	return OK;
}

(2)销毁线性表

void DestroyList(SqList &L) {
	if(L.elem) {
		free(L.elem); //释放存储空间
	}
}

(3)清空线性表

void ClearList(SqList &L) {
	L.length = 0;
}

(4)求线性表长度

int GetLnegth(SqList L) {
	return L.length;
}

(5)判断线性表L是否为空

int IsEmpty(SqList L) {
	if(L.length == 0) {
		return 1;
	}
	return 0;
}