一、线性表
线性表是一个由N个数据元素组成的有限序列。其中一个数据元素可以由若干个数据项组成。常把数据元素称为记录,含有大量记录的线性表称为文件。
1 、线性表的顺序存储结构表示与实现:
typedef struct SqList
{
ElemType *elem;int length;int listsize;
}SqList;
线性表的基本操作:
1. 构造一个空线性表并初始化
InitList(Sqlist *L)
{
L->elem = malloc(sizeof(ElemType) * LIST_INIT_SIZE));
if(!L->elem) return OVERFLOW;
L->length = 0;
L->listsize = LIST_INIT_SIZE;
}
2. 销毁线性表
DestroyList(SqList *L)
{
free(L->elem);
L->elem = NULL;
L->length = 0;
L->listsize = 0;
}
3. 置空线性表
ClearList(SqList *L)
{
L->length = 0;
}
4. 检查线性表是否为空
int ListEmpty(SqList *L)
{
if(L->length == 0)
return TRUE;
else
return FALSE;
}
5. 线性表长度
int ListLength(SqList L)
{
return L.length;
}
5. 用E返回线性表L中第I个数据元素的值
GetElem(SqList L, int i, ElemType *e)
{
ElemType *p = L.elem;
if(i < 1 || i > L.length)
return ERROR;
*e = *(p + i - 1);
return OK;
}
6. 返回L中与e满compare()的数据元素的位序。若不存在则返回0;
For compare function, if equal, return 1, else return 0;
LocateElem(SqList L, ElemType e, int(*compare)(ElemType,ElemType))
{
int i;
if(L.length > 0)
ElemType *p = L.elem;
while(i <= L.length && !compare(*p, e)
{
++i;
++p;
}
if(i > L.length)
return FALSE;
else
{
return i;
}
}