文章目录
前言
线性表的存储结构分为顺序存储和链式存储,顺序存储需要一组地址连续的存储单元依次存储线性表的数据结构,而链式存储结构使用一组任意的存储单元存储线性表的数据元素。
一、线性表的顺序存储
Ⅰ.结构体定义与初始化
typedef struct{
ElemType *elem;//存储空间基址
int length;//当前长度
int listsize;//当前分配的存储容量
}SqList;
Status InitList(SqList &L)
{
//构造一个空的线性表
L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
1.增
/*线性表插入操作*/
Status InsertList(SqList &L,ElemType e,int i)
{
//首先判断插入位置i是否合理
if(i<0||i>L.length+1) exit(ERROR);
//如果内存不够再追加内存
if(L.length >= L.listsize)
{
ElemType *newbase;
newbase = (ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize = L.listsize+LISTINCREMENT;
}
ElemType *p,*q;
q = &L.elem[i-1];//q为插入数据位置(注意别忘了取址符号)
p = &L.elem[L.length-1];//p当前为队尾位置
for(p;p>=q;p--) *(p+1) = *(p);//核心操作步骤
*q = e;
L.length++;
return OK;
}
2.删
Status DeleteList(SqList &L,ElemType &e, int i)
{
//在线性表中删除第i个元素,并用e返回其值
//首先判断i的值是否合理
if(i<0||i>L.length) exit(ERROR);
ElemType *p,*q;
q = &L.elem[i-1];
e = *q;
p = &L.elem[L.length-1];
for(q++;q<=p;q++) *(q-1) = *q;
L.length--;//删除操作完成后顺序表长度减一
return OK;
}
3.改
Status ChangeList(SqList &L,ElemType e)
{
//查找到顺序表中的特定数值e,然后修改为新值
int i = 0;
for(i;L.elem[i]!=e;i++);//查找线性表中是否存在该元素
if(i>=L.length)
{
cout<<"没有您要找的数据"<<endl;
}
else
{
cout<<"你要将该数据更改为?"<<endl;
cin>>L.elem[i];
cout<<"修改成功,已将"<<e<<"修改为"<<L.elem[i]<<endl;
}
}
4.查
//查找一个元素
int compare(ElemType a,ElemType b)//定义一个compare函数
{
if(a==b)
return OK;
else
return 0;
}
Status LocateElemList(SqList L,ElemType e,Status(*compare)(ElemType,ElemType))
{
//在线性表中查找第一个值与e满足compare关系的元素的位序
//若找到,则返回其在L中的位序,否则返回0
int i =1;
ElemType *p = L.elem