线性表的顺序(存储)表示——顺序表
用一组地址连续的存储单元依次存储线性表的数据元素
位序相继的两个数据元素存储位置相邻
以线性表中第一个元素的存储位置作为线性表的起始存储地址,称为基地址。
线性表中所有元素的存储地址都可以通过基地址得到
★顺序表是具有顺序结构的线性表
顺序表的存储结构定义为:
typedef struct
{
ElemType *elem;//存储空间基址
int length;//当前长度
int listsize;//当前分配存储容量(以sizeof(ElemType)为单位)
}Sqlist;
相关的定义如下
# define LIST_INIT_ZIZE 100//线性表储存空间的初始值
# define LISTINCREMENT 10 //线性表储存空间的分配增量
#define OVERFLOW 1
#define ERROR -1
#define OK 1
typedef int Status;
typedef int ElemType;
//Status,ElemType :函数返回值(一般替换int型)
顺序表基本操作
1.创建空表
//创建一个空的线性表
Status CreateList(Sqlist &L)
{
L.elem = (ElemType *)malloc(sizeof(ElemType)*LIST_INIT_ZIZE);
if (!L.elem) exit(OVERFLOW);//内存分配失败
L.length = 0;//将当前表长置0
L.listsize = LIST_INIT_ZIZE;//初始化表的存储容量
}
2.求线性表的长度
//求线性表的长度
Status Listlength(Sqlist L)
{
return L.length;
}
3.判断是否为满表
//判断是否为满表
bool IsfullList(Sqlist L)
{
if (L.length == LIST_INIT_ZIZE)return true;
else
return false;
}
4.查找第i个元素并用e表示其值
//查找第i个元素并用e表示其值
Status Find(Sqlist L, int i, ElemType e)
{
if (i<1 || i>L.length)
return ERROR;
e = *(L.elem + i - 1);
return 0;
}
5.查找线性表L中满足函数的元素的位置
Status LocateElem_sq(Sqlist L, ElemType e, Status(*compare)(ElemType, ElemType))
{
//在顺序线性表L中查找第1个值与e满足compare()的元素的为序
//若找到,则返回其在L中的位序,否则返回0
int i = 1;//i的初值为第1个元素的位序
ElemType *p = L.elem; //p的初值为为第1个元素的存储位置
while (i <= L.length && !(*compare)(*p++, e))
++i;
if (i <= L.length)
return i;
else
return 0;
}
6.在L的第i个位置插入新元素,表长加1
//在L的第i个位置插入新元素,表长加1
Status ListInsert(Sqlist &L, int i, ElemType e)
{
ElemType *newbase, *p, *q;
if (i < 1 || i>L.length)return ERROR;
//接下来判断是否满表了,满表需要增加存储容量
if (L.length >= L.listsize)
{
newbase = (ElemType*)realloc(L.elem,(L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase) exit(OVERFLOW);//存储分配失败
L.elem = newbase;//新基址
L.listsize += LISTINCREMENT;
}
p = L.elem+i-1;//q为插入位置
for (q=L.elem+L.length-1;q>=p;--q)
*(q + 1) = *q; //插入位置及之后的元素右移
*p = e; //插入e
++L.length; //表长增1
return OK;
}
7.删除顺序表L第i个位置的元素,表长减1
//删除顺序表L第i个位置的元素,表长减1
Status ListDelete(Sqlist &L, int i,ElemType e)
{
ElemType *p, *q;
if (i < 1 || i>L.length)return ERROR;
p = L.elem + i - 1;//删除元素的位置
e = *p;//删除元素赋给e
q = L.elem + L.listsize - 1;//表尾位置
for (++p; p <= q; ++p)
*(p - 1) = *p;//删除元素后的元素左移
--L.length;//表长减1
return e;
}
输入及主函数
void input(Sqlist L)
{
int i = 1;//i的初值为第1个元素的位序
ElemType *p = L.elem; //p的初值为为第1个元素的存储位置
while (i <= L.length)
{
cout << *(p++) << " ";
++i;
}
cout << endl;
}
void main()
{
Sqlist L;
CreateList(L);
ListInsert(L, 1, 2);//在顺序线性表L中第i个位置之前插入新的元素e
ListInsert(L, 2, 3);//在顺序线性表L中第i个位置之前插入新的元素e
ListInsert(L, 3, 4);//在顺序线性表L中第i个位置之前插入新的元素e
ListInsert(L, 4, 5);//在顺序线性表L中第i个位置之前插入新的元素e
cout << "线性表中的所有元素为:";
input(L);
int e = LocateElem_sq(L, 3, (*compare));//在顺序线性表L中查找第1个值与e满足compare()的元素的为序
cout << "线性表中与3相等的元素的位序为:" << e << endl;
system("PAUSE");
return;
}