直接上代码:
#include <stdio.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
#define ERROR 0
#define OK 1
typedef int Status;
typedef int ElementType;
typedef struct
{
ElementType *base;// 顺序表的起始地址
int length;// 当前的长度
int listSize;// 初始化时制定的长度
} SequentialList;
// 创建顺序表
void initList(int initLength, SequentialList *list) {
list->length = 0;
list->listSize = initLength;
list->base = (ElementType *)malloc(list->listSize * sizeof(ElementType));// 分配这个存储空间(不像Java中直接使用数组来写,C语言写的话更加能理解工作机制)
}
// 判断是否为空
_Bool listEmpty(SequentialList *list) {// 使用的是_Bool而不是bool
return list->length == 0;
}
// 返回顺序表的当前长度
int listLength (SequentialList *list) {
return list->length;
}
// 得到指定位置的值
ElementType listGetElement(SequentialList *list, int index) {
if (index < 1 || index > (list->length+1)) {
printf("不存在这个位置");
return ERROR;
}
return list->base[index-1];
}
// 得到指定值的位置
int listGetIndex(SequentialList *list, ElementType element) {
for (int i = 0; i < list->length; i++) {
if(list->base[i] == element) {
return i+1;
}
}
return ERROR;
}
// 插入元素
Status listInsert(SequentialList *list, int index, ElementType element) {
if (list->length == list->listSize) {
printf("已经满了,不能再插入");
return ERROR;
} else if (index<1 || index>(list->length + 1)) {// 这里的index是面向用户的,所以和数组中的序号相差一位
printf("插入的位置不对");
return ERROR;
}
// 插入的算法
for (int i = (list->length - 1); i >= (index-1); i--) {
list->base[i+1] = list->base[i];
}
list->base[index-1] = element;
list->length++;
return OK;
}
// 删除元素
Status listDelete(SequentialList *list, int index) {
if (index<1 || index>(list->length+1)) {
printf("删除的序号不对");
return ERROR;
}
for (int i = index-1; i < list->length; i++) {
list->base[i] = list->base[i+1];
}
list->length--;
return OK;
}
// 遍历打印顺序表
void listTraverse(SequentialList *list) {
for(int i = 0; i < list->length; i++) {
printf("%d ", list->base[i]);
}
printf("\n");
}
// 将顺序表清空
void listClear(SequentialList *list) {
list->length = 0;
}
// 销毁顺序表
Status listDestroy(SequentialList *list) {
listClear(list);// 先清空数组
list->listSize = 0;// 将初始长度设置为0
free(list->base);// 释放malloc出的空间
if (list->base == NULL && list->length == 0 && list->listSize == 0) {// 最后的确认
return OK;
} else {
return ERROR;
}
}
int main(int argc, const char * argv[]) {
/*
SequentialList list;
initList(100, &list);// 初始化
listInsert(&list, 1, 1);// 插入
listInsert(&list, 2, 2);
listInsert(&list, 3, 3);
listInsert(&list, 4, 4);
listTraverse(&list);
listInsert(&list, 2, 200);
listTraverse(&list);
listDelete(&list, 2);
listDelete(&list, 2);
listTraverse(&list);
printf("%d\n",listGetElement(&list, 2));
printf("%d\n",listGetIndex(&list, 3));
*/
return 0;
}
网友评论