用结构体实现线性表的顺序表示和实现。
功能有创建,插入,删除,查找
#include <cstring>
#include <cstdio>
#include <string>
#include <stdlib.h>
#define LIST_INIT_SIZE 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
#define ElemType int
typedef struct{
ElemType *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量(sizeof(ElemType))
}SqList;
//创建
bool InitList(SqList &L){
L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem) exit(1); //存储分配失败
L.length = 0; //空表长度为0
L.listsize = LIST_INIT_SIZE; //初始存储容量
return true;
}//InitList
//增加
bool ListInsert(SqList &L,int i,ElemType e){
if(i<1 || i>L.length+1) return false;
if(L.length >= L.listsize){ //当前存储空间已满,增加分配
ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newbase) exit(1); //存储分配失败
L.elem = newbase; //新基地址
L.listsize += LISTINCREMENT; //增加存储容量
}
ElemType *q = &(L.elem[i-1]); //q为插入位置
for(ElemType *p= &(L.elem[L.length-1]); p>=q; --p)
*(p+1) = *p; //插入位置及之后的元素后移
*q = e; //插入e
++L.length; //表长+1
return true;
}//ListInsert
//删除
bool ListDelete(SqList &L,int i,ElemType &e){
if((i<1) || (i>L.length)) return false;
ElemType *p = &(L.elem[i-1]);
e = *p;
ElemType *q = L.elem + L.length - 1;
for(++p; p<= q;++p)
*(p-1) = *p;
--L.length;
return true;
}//ListDelete
bool compare(ElemType e1,ElemType e2)
{
if(e1 < e2 ) return 0;
else return 1;
}
//查找
int LocateElem(SqList &L,ElemType e,bool (* compare)(ElemType,ElemType)){
int i=1;
ElemType *p = L.elem;
while(i <= L.length && !(*compare)(*p++,e))
++i;
if(i<=L.length) return i;
else return 0;
}//LocateElem
int main()
{
SqList L;
ElemType elem;
int i;
InitList(L);
printf("总长:%d ,存储容量:%d\n",L.length,L.listsize);
i=1;elem=1;
if(ListInsert(L,i,elem)) printf("%d 插入到 %d 成功\n",elem,i);
else printf("%d 插入到 %d 失败\n",elem,i);
i=2;elem=4;
if(ListInsert(L,i,elem)) printf("%d 插入到 %d 成功\n",elem,i);
else printf("%d 插入到 %d 失败\n",elem,i);
i=3;elem=6;
if(ListInsert(L,i,elem)) printf("%d 插入到 %d 成功\n",elem,i);
else printf("%d 插入到 %d 失败\n",elem,i);
i=2;elem=3;
if(ListInsert(L,i,elem)) printf("%d 插入到 %d 成功\n",elem,i);
else printf("%d 插入到 %d 失败\n",elem,i);
i=8;elem=8;
if(ListInsert(L,i,elem)) printf("%d 插入到 %d 成功\n",elem,i);
else printf("%d 插入到 %d 失败\n",elem,i);
for(ElemType *p=L.elem; p<=&(L.elem[L.length-1]);p++){
printf("%d ",*p);
}printf("\n");
printf("总长:%d ,存储容量:%d\n",L.length,L.listsize);
i=5;
printf("第一个比 %d 大或等的下标 %d\n",i,LocateElem(L,i,compare));
i=3;
printf("第一个比 %d 大或等的下标 %d\n",i,LocateElem(L,i,compare));
i=2;
printf("第一个比 %d 大或等的下标 %d\n",i,LocateElem(L,i,compare));
i=7;
printf("第一个比 %d 大或等的下标 %d\n",i,LocateElem(L,i,compare));
i=6;
printf("第一个比 %d 大或等的下标 %d\n",i,LocateElem(L,i,compare));
ListDelete(L,2,elem);
printf("删除elem: %d ",elem);
printf("总长:%d ,存储容量:%d\n",L.length,L.listsize);
return 0;
}
结果: