# define MAX_SIZE 255
typedef struct {
int id;
char *name;
} ElementType;
typedef struct {
ElementType datas[MAX_SIZE];
int length;
} SeqList;
void InsertElement(SeqList * seqList , int index,ElementType elementType){
isOutOfRange(seqList,index);
for (int i = seqList->length -1 ; i >= index ; i -- ) {
seqList->datas[i + 1] = seqList->datas[i];
}
seqList->datas[index] = elementType;
seqList->length ++ ;
}
void InitList(SeqList * seqList ,ElementType * elemArray,int length){
if(length > MAX_SIZE){
printf("超出了数组的最大容量,初始化失败!\n");
return;
}
seqList ->length = 0 ;
for (int i = 0; i < length - 1; ++i) {
InsertElement(seqList,i,elemArray[i]);
}
}
ElementType * deleteList(SeqList * seqList,int index){
isOutOfRange(seqList,index);
ElementType * delElement = (ElementType * )malloc(sizeof(ElementType));
*delElement = *searchElem(seqList,index);
for (int i = index ; i <= seqList -> length -1 ; ++i) {
seqList ->datas[i] = seqList->datas[i+1];
}
seqList->length --;
return delElement;
}
int getLength(SeqList * seqList){
if(seqList == NULL){
return 0;
}
return seqList->length;
}
int isEmpty(SeqList * seqList){
return getLength(seqList) == 0 ? TRUE:FALSE;
}
void clearList(SeqList * seqList){
if(seqList == NULL) return;
seqList->length = 0;
}
void isOutOfRange(SeqList * seqList,int index){
if(seqList->length+1 > MAX_SIZE){
printf("数组已满,插入元素失败!\n");
return;
}
if(index < 0 || index > MAX_SIZE){
printf("只能在允许的下标范围内插入元素[0,%d]\n");
return;
}
if(index > seqList->length){
printf("插入的下标超过了数组的最大长度-1,插入失败\n");
return;
}
}
ElementType * searchElem(SeqList * seqList,int index){
isOutOfRange(seqList,index);
return &seqList->datas[index];
}
void PrintList(SeqList * seqList){
for (int i = 0; i < seqList->length; ++i) {
printf("%d\t%s\n",seqList->datas[i].id,seqList->datas[i].name);
}
}
ElementType dataArray[] = {
{1,"祈风"},
{2,"美队"},
{3,"奇异博士"},
{4,"蓝轩宇"},
{5,"唐舞麟"}
};
void TestSeqList();
int main() {
TestSeqList();
return 0;
}
void TestSeqList(){
SeqList seqList ;
InitList(&seqList,dataArray,sizeof(dataArray) / sizeof(dataArray[0])+1);
PrintList(&seqList);
printf("********\n");
ElementType * ele = deleteList(&seqList,2);
printf("被删除的元素是:\n")
printf("%d\t%s\n",ele->id,ele->name);
printf("\n");
PrintList(&seqList);
printf("长度是****%d\n",seqList.length);
free(ele);
}
- 结果
心得
- 实现顺序表,感觉有点像面向接口编程,首先我将那两个结构放在头文件,那些方法也放在另一个头文件,但是不去写它的实现,而是在另一个.c文件里引入头文件,然后实现它,这就有点像一个接口,而.c文件就相当于一个实现类,这样实现的话层次很清楚,而且在测试文件里我只可以导入头文件,具体的实现用户是看不到的,这样就是将你的代码封装了起来,安全性得到了保障。
- 下面看看我的结构
头文件:
一些没有实现的方法
具体方法实现
测试